【问题标题】:componentDidUpdate vs componentWillReceiveProps use case in reactreact 中的 componentDidUpdate 与 componentWillReceiveProps 用例
【发布时间】:2018-08-29 09:24:20
【问题描述】:

这就是我们使用componentWillReceiveProps的方式

componentWillReceiveProps(nextProps) {
  if(nextProps.myProp !== this.props.myProps) {
    // nextProps.myProp has a different value than our current prop
  }
}

componentDidUpdate很像

componentDidUpdate(prevProps) {
  if(prevProps.myProps !== this.props.myProp) {
    // this.props.myProp has a different value
    // ...
  }
}

我可以看到一些差异,比如如果我在 componentDidUpdate 中执行 setState,渲染将触发两次,并且 componentWillReceiveProps 的参数是 nextProps,而 componentDidUpdate 的参数是 prevProp,但我真的不知道什么时候使用它们.我经常使用componentDidUpdate,但是使用prevState,比如更改下拉状态并调用api

例如。

componentDidUpdate(prevProps, prevState) {
      if(prevState.seleted !== this.state.seleted) {
        this.setState({ selected: something}, ()=> callAPI())
      }
    }

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

两者的主要区别在于:

  • 在组件的生命周期中调用它们时
  • 如何更新组件state

什么时候叫他们?

正如名字所暗示的那样——正如你可能知道的,因为你提到“如果我在 componentDidUpdate 中设置状态,渲染将触发两次”——componentDidUpdate 在组件更新之后被调用 (收到新的道具或状态)。这就是为什么这个函数的参数是prevPropsprevState

因此,如果您想在组件收到新道具之前做某事,您可以使用componentWillReceiveProps,如果您想在它收到新道具之后做某事道具或状态,你会使用componentDidUpdate

他们如何更新state

这里的主要区别是:

这很重要,因为在尝试将状态与组件道具的其他部分同步时可能会出现一些问题。

【讨论】:

  • 在组件更新之前做事的一些例子是更新组件更新后无法完成的?
猜你喜欢
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
相关资源
最近更新 更多