首页 > 解决方案 > 使用 componentWillReceiveProps 更新状态

问题描述

我正在查看其他代码,该代码更新了反应生命周期中的对象状态:componentWillReceiveProps。我对 react 和 redux 还很陌生,但我认为你在 reducer 中进行了所有状态更新,而对其本地状态毫无用处。有人能告诉我他为什么在 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})
  }

标签: reactjs

解决方案


好吧,首先,componentWillrecieveProps它已被弃用,因为它可能会导致一些问题,看看这里。相反,React 文档指出您应该使用componentDidUpdate安全使用的方法。

并回答您的问题,如果您查看了该人使用 redux 的代码,那么他使用了已弃用的方法,因为当您通过 将组件绑定到 redux goblal state (store) 时mapStateToProps,它的属性将绑定到该组件道具。所以,换句话说,每当全局状态发生变化时,组件 props 也会发生变化,如果你想在你的组件逻辑中“跟踪”这些变化,你必须知道它的 props 什么时候会发生变化,这就是你使用componentWillRecievePropsorcomponentDidUpdate方法的原因.

以下是示例代码应该如何完成的componentDidUpdate

componentDidUpdate(prevProps) { //prevProps is the previous props of the component before being updated
   //so, if this.props != prevProps it means that component props have been updated

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

推荐阅读