问题
In my react js app, I can't seem to use the state value as props for the child component.
In the parent component, constructor
, the app has a null state called selectedWarehouseID
.
This state(selectedWarehouseID
) should update with some information in the componentWillMount()
method.
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 }
/>
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:
Possible solutions are:
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():
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.
Like this:
componentWillReceiveProps(newProps){
this.setState({
value: newProps.productsByWarehouse
});
}
Note: Replace value by the actual key in which you are storing the value.
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
.
来源:https://stackoverflow.com/questions/44536714/cant-use-state-value-as-props-for-child-component