2017-03-06 55 views
1

我目前有两个React组件,一个维护用户输入的对象列表,例如:[{"good1":"$10"},{"good2":"$15"}],另一个组件让用户创建列表并将商品用作标签。然而,我在如何将处于GoodManage状态的数据传递给ListManager时遇到了问题,我也有布局的包装器。我试图将LayoutManager中的状态传递给GoodManager并更新商品列表,并将相同的列表发送到ListManager,但它似乎只能工作一次。将同一数据传递给两个React组件的最佳方法?

class LayoutManager extends React.Component{ 
    constructor(){ 
     super(); 
     this.state = {"goods":[{"good1":"$1"}]}; 
    } 
    updateGoods(goods){ 
     this.setState({"goods":goods}); 
    } 
    render(){ 
     return (
      <div className="layout-manager"> 
       <div className="good-manager container"> 
        <GoodManager update={this.updateGoods.bind(this)} goods={this.state.goods}/> 
       </div> 
       <div className="list-mananger container"> 
        <ListManager goods={this.state.goods}/> 
       </div> 
      </div> 
     ) 
    } 
} 

回答

1

像你描述它的工作只是第一次,它意味着你存储在constructorListManager组件的state变量的商品价值,它只会保存因为constructor只得到所谓的第一rendering不是最初名单在re-endering,所以你需要使用lifecycle方法componentWillReceiveProps,它会被调用时的任何变化发生props值,这时候你需要更新state值,在ListManager组件使用此方法:

componentWillReceiveProps(nextProp){ 
    this.setState({goods: nextProps.goods}); 
} 

参考:https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops