2017-09-11 133 views
1

我想傳遞的address更新狀態父組件,該子組件的center財產。更具體地說,從App組件到BaseMap組件。但是,我似乎無法使其工作。新鮮的眼睛,可以幫助將不勝感激!通在更新父狀態子成分反應JS

這是我的代碼(我刪除了取功能,它工作得很好,所以它不會打擾你,我只是需要更新我的孩子組件的狀態。):

家長:

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     avatar: '', 
     username: 'nickname93', 
     realName: '', 
     location: '', 
     followers: '', 
     following: '', 
     repos: '', 
     address: '' 
     } 
    } 

    render() { 
    return (
     <div> 
     <SearchBox fetchUser={this.fetchUser.bind(this)}/> 
     <Card data={this.state} /> 
     <BaseMap center={this.state.address}/> 
     </div> 
    ); 
    } 

    fetchApi(url) { 
    // some fetch functionality 
    } 

    fetchUser(username) { 
    let url = `https://api.github.com/users/${username}`; 

    this.fetchApi(url); 
    } 

    componentDidMount() { 
    let url = `https://api.github.com/users/${this.state.username}`; 

    this.fetchApi(url); 
    } 

} 

和子組件:

export default class BaseMap extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      center: [24, 56], 
      zoom: 11 
     } 
    } 

    render() { 
     return (
      <Col md={10} mdPull={1}> 
       <div className="map"> 
        <GoogleMap 
        bootstrapURLKeys={'AIzaSyBhzwgQ3EfoIRYT70fbjrWASQVwO63MKu4'} 
        center={this.state.center} 
        zoom={this.props.zoom}> 
        </GoogleMap> 
       </div> 
      </Col> 
     ); 
    } 
} 

回答

2

你的價值被傳遞從父組件App你的孩子組件BaseMap

只需使用this.props.center而不是this.state.center即可訪問或使用從父項傳遞給子組件的屬性(也稱爲props)。

export default class BaseMap extends React.Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     center: [24, 56], 
     zoom: 11 
    } 
} 

render() { 
    return (
     <Col md={10} mdPull={1}> 
      <div className="map"> 
       <GoogleMap 
       bootstrapURLKeys={'AIzaSyBhzwgQ3EfoIRYT70fbjrWASQVwO63MKu4'} 

       center={this.state.center} // this is [24,56] 

       centerFromParentComponent = {this.props.center} // this is the property passed from parent component 

       zoom={this.props.zoom}> 
       </GoogleMap> 
      </div> 
     </Col> 
    ); 
} 

}

使用this.props您可以訪問您從父組件傳遞任何屬性(如狀態,變量或方法)。

你也可能想看看componentWillReceiveProps()方法。您可能很快就會需要它。

1

使用this.props.center,而不是this.state.center如果你想BaseMap從父接收狀態更新。看起來你想爲center道具設置默認值。這裏是the doc來聲明默認道具。