不能将状态值用作子组件的道具 [英] Can't use state value as props for child component
问题描述
在我的react js app中,我似乎无法将状态值用作子组件的道具。
In my react js app, I can't seem to use the state value as props for the child component.
在父组件中,构造函数
,该应用程序的状态为 selectedWarehouseID
。
In the parent component, constructor
, the app has a null state called selectedWarehouseID
.
此状态( selectedWarehouseID
)应该使用 componentWillMount()
方法中的一些信息进行更新。
This state(selectedWarehouseID
) should update with some information in the componentWillMount()
method.
现在,在父组件的 render
方法中,我将另一个具有此状态的子组件嵌入到道具中。
Now, in the render
method of the parent component I am embedding another child component that has this state as a props.
<ItemChooser
productsByWarehouse = { this.state.selectedWarehouseID }
/>
现在问题是,在子组件中,这个值。 props.productsByWarehouse
总是 null
。我找到了一个很好的解释为什么会发生这种情况,但是如何等待父母更新的数据 componentWillMount()
访问子组件道具中传递的状态的更新值?
Now here's the problem, in the child component, the value of this.props.productsByWarehouse
is always null
. I found a nice explanation of why this happens, but how to wait for the data that updates in the parents componentWillMount()
to access the updated value of the state that being passed in the child component props?
推荐答案
可能的解决方案是:
1。您正在存储道具
子组件的 state
中的值,因此,只要对 props
值发生任何更改,就更新子组件的状态(状态为父母)。为此使用 componentWillReceiveProps
生命周期方法。
1. You are storing the props
value in state
of child component so, Update the state of child component whenever any change happen to props
values (state of parent). For that use componentWillReceiveProps
lifecycle method.
componentWillReceiveProps():
在安装的组件收到新的道具之前被调用。如果你需要
来更新状态以响应prop更改(例如,重置
),你可以比较this.props和nextProps并使用this.setState执行状态
转换( )在这种方法中。
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
});
}
注意:用实际键替换值您存储的值。
Note: Replace value by the actual key in which you are storing the value.
2. 不要存储道具
子组件状态中的值,直接使用 this.props.productsByWarehouse
,每当您更改父状态值时,子将自动获取中的更新值道具
。
2. Don't store the props
values in state of child component, directly use this.props.productsByWarehouse
, Whenever you change the parent state values, child will automatically get the updated value in props
.
这篇关于不能将状态值用作子组件的道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!