将相同数据传递给两个React组件的最佳方法是?

时间:2017-03-06 05:29:15

标签: reactjs

我目前有两个React组件,一个维护用户输入的对象列表ex:[{"good1":"$10"},{"good2":"$15"}],另一个组件允许用户创建列表并将商品用作标签。但是我在如何将GoodManage状态的数据传递给ListManager时遇到了麻烦,我还有一个布局包装器。我尝试将状态从LayoutManager传递到GoodManager并让它更新商品列表,并将相同的列表发送到ListManager,但它似乎只工作一次。

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 个答案:

答案 0 :(得分:1)

正如您所描述的仅在第一次工作时,这意味着您将货物值存储在stateListManager组件的constructor变量中,它将仅保存初始列表constructor只能在第一个rendering而不是re-endering上被调用,因此您需要使用lifecycle方法componentWillReceiveProps,当props发生任何变更时,它会被调用{1}}值,此时您需要更新state值,请在ListManager组件中使用此方法:

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

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