将状态与子组件连接

时间:2016-12-16 11:43:31

标签: reactjs redux react-redux

我正在尝试将商店与子组件绑定。 我有AppContainer.js:

// here I'm binding store value to props
function mapStateToProps(store, props){
    return {
        user: store.userInfo.loaded ? store.userInfo.userData : '%noname%'
    }
}

componentDidMount(){
    store.dispatch(fetchUser()).then(() =>
        console.log(store.getState())
    )
}

render(){
    return <Application routes={this.props.routes} user={this.props.user}/>
}

export default connect(mapStateToProps)(ApplicationContainer);

在Application.js中,我将params传递给孩子和孩子:

render(){

    return  <div className="component">
                <Header title="Home" user={this.props.user} routes={this.props.routes}/>
                {this.props.children} // Here is Home Component
            </div>;
}

想要在Home.js(其中一个孩子)中获得州值:

render() {
        return <h5>Welcome back, {this.props.user.name}</h5>
    }

所以,问题是:   将商店值推送到子组件的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用React.children和cloneElement来实现:

return (
  <div className="component">
    <Header title="Home" user={this.props.user} routes={this.props.routes}/>
    {React.Children.map(this.props.children, child =>
      React.cloneElement(child, {
        ...this.props
      })
    )}
  </div>;
);
相关问题