2017-03-06 59 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