2016-12-16 6 views
0

子コンポーネントとストアをバインドしようとしています。 私が持っているAppContainer.js:Application.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); 

私は直接の子供と子供たちにの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

あなたはそれを達成するために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>; 
); 
関連する問題