我目前有两个React组件,一个维护用户输入的对象列表,例如:[{"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>
)
}
}发布于 2017-03-06 13:40:12
由于您第一次描述了它的工作原理,这意味着您将商品值存储在constructor的ListManager组件的state变量中,它将只保存初始列表,因为constructor只在第一个rendering上被调用,而不是在re-endering上,所以您需要使用lifecycle方法componentWillReceiveProps,它将在props值发生任何变化时被调用,此时您需要更新<代码>D9值,在<代码>D10组件中使用此方法:
componentWillReceiveProps(nextProp){
this.setState({goods: nextProps.goods});
}参考:https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops
https://stackoverflow.com/questions/42618164
复制相似问题