使用componentWillReceiveProps更新状态

时间:2018-09-10 16:23:46

标签: reactjs

我正在查看其他代码,这些代码在react lifecyle:componentWillReceiveProps中更新了对象的状态。我对React和Redux相当陌生,但是我认为您可以在化简器中进行所有状态更新,而无需使用其本地状态。有人可以告诉我为什么他在componentWillReceiveProps中这样做吗?谢谢

 componentWillReceiveProps(nextProps) {
    if(this.props.isEditingbook && !nextProps.isEditingbook) {
      let book = this.props.index.bookDictionary[this.props.currentbook.id] 
      book.name = this.state.model.name.value
    }
    this.setState({ ...this.state, ...nextProps})
  }

1 个答案:

答案 0 :(得分:1)

首先,不推荐使用componentWillrecieveProps,因为它可能会引起一些问题,请查看here。相反,React文档指出您应该使用componentDidUpdate,这是一种安全使用的方法。

回答您的问题,如果您查看该人使用redux的代码,那么他使用了不推荐使用的方法,因为当您通过mapStateToProps将组件绑定到redux goblal状态(存储)时,它的属性就被绑定了到那个道具。因此,换句话说,每当全局状态发生变化时,组件属性也会发生变化,并且如果您要在组件逻辑中“跟踪”这些更改,则必须知道何时属性会发生变化,这就是为什么使用{{ 1}}或componentWillRecieveProps方法。

以下是使用componentDidUpdate完成示例代码的方式:

componentDidUpdate
相关问题