javascript - 无法使用状态值作为子组件的 props

标签 javascript reactjs

在我的 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/

相关文章:

javascript - Nodejs中如何将json对象数组转换为String?

reactjs - Apollo Client 如何将本地缓存的突变发送到服务器

reactjs - React 中是否可以将初始状态设为空对象?

javascript - 在通常放置 var 的地方使用 type 关键字是什么?

javascript - 方法多次触发

javascript - 验证密码并重新输入密码

javascript - React setState 不影响 Children

reactjs - 如何在 React Router v4 中推送历史记录?

javascript - Lodash Js 使用数组和对象创建树结构

javascript - html 中的变量用于引用 javascript 文件