componentWillRecieveProps与getDerivedStateFromProps

时间:2018-06-21 14:49:15

标签: reactjs

不建议使用

componentWillRecieveProps,而主张使用getDerivedStateFromProps。

但是当更改道具时会调用componentWillRecieveProps,但是即使在任何状态更改时也会调用getDerivedStateFromProps。

我的要求是在道具更改时重置状态。所以我怎么知道道具真的变了。

我不赞成将props值存储在状态中,因为这会不必要地使状态变大,并且我仍然没有给状态管理(Redux或Context API)一个想法

请告知

1 个答案:

答案 0 :(得分:2)

  

我怎么知道道具真的变了

比较以前的道具和新的道具。

对于最简单的用例,只需使用componentDidUpdate(),并进行属性比较:

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

根据React Doc,可以在setState()内执行副作用或componentDidUpdate()

setState()可能导致重新渲染,从而影响组件性能。在这种情况下,性能实际上是很重要的事情,请继续阅读:https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state