使用componentWillReceiveProps更新状态

问题描述 投票:0回答:1

我正在查看其他代码,他们更新了反应生命周期中的对象状态:componentWillReceiveProps。我是新手反应和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
1个回答
1
投票

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

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

以下是使用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})
  }
© www.soinside.com 2019 - 2024. All rights reserved.