2017-09-11 48 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来声明默认道具。