不能将状态值用作子组件的道具

Can't use state value as props for child component

在我的 React js 应用程序中,我似乎无法将状态值用作子组件的道具。

在父组件 constructor 中,应用程序有一个名为 selectedWarehouseID 的空状态。

此状态 (selectedWarehouseID) 应使用 componentWillMount() 方法中的一些信息进行更新。

现在,在父组件的 render 方法中,我嵌入了另一个将此状态作为道具的子组件。

<ItemChooser
  productsByWarehouse = { this.state.selectedWarehouseID }
/>

现在问题来了,在子组件中,this.props.productsByWarehouse的值总是null。我找到了一个很好的 来解释为什么会发生这种情况,但是如何等待父组件中更新的数据 componentWillMount() 来访问在子组件道具中传递的状态的更新值?

可能的解决方案是:

1. 您将 props 值存储在 child 组件的 state 中,因此,更新 [=40= 的状态] 组件,只要 props 值发生任何变化(parent 的状态)。为此使用 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
   });
}

注意:用存储值的实际键替换值。

2.不要将props值存储在child组件的状态中,直接使用this.props.productsByWarehouse,每当你改变parent状态值,child会自动获取props中的更新值。