在我的 React js 应用程序中,我似乎无法使用状态值作为子组件的 Prop 。
在父组件构造函数
中,应用程序有一个名为selectedWarehouseID
的空状态。
此状态 (selectedWarehouseID
) 应使用 componentWillMount()
方法中的一些信息进行更新。
现在,在父组件的 render
方法中,我嵌入了另一个具有此状态作为 props 的子组件。
<ItemChooser
productsByWarehouse = { this.state.selectedWarehouseID }
/>
现在问题来了,在子组件中,this.props.productsByWarehouse
的值始终为null
。我找到了一个不错的explanation为什么会发生这种情况,但是如何等待父组件 componentWillMount()
中更新的数据来访问子组件 props 中传递的状态的更新值?
最佳答案
可能的解决方案是:
1. 您将 props
值存储在子组件的 state
中,因此,只要发生任何更改,就更新子组件的状态props
值(父级的状态)。为此,请使用 componentWillReceiveProps
生命周期方法。
<强> componentWillReceiveProps():
is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.
像这样:
componentWillReceiveProps(newProps){
this.setState({
value: newProps.productsByWarehouse
});
}
注意:将 value 替换为您存储值的实际键。
2.不要将props
值存储在子组件的state中,直接使用this.props.productsByWarehouse
,每当你改变时父级状态值,子级将自动获取 props
中更新的值。
关于javascript - 无法使用状态值作为子组件的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44536714/