2016-12-16 177 views
0

我試圖綁定存儲與兒童組件。 我有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

你可以使用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>; 
);