如何检查componentWillReceiveProps中更改了哪些道具

问题描述 投票:29回答:6

有没有办法检查componentWillReceiveProps内哪些道具改变了(不在其他地方存放旧道具)?

componentWillReceiveProps (newProps) {
  if( /* newProps.profileImage is different to previous props */ ) /* do stuff */
}
reactjs
6个回答
33
投票

请注意,函数componenWillReceiveProps将来会被弃用。引用the official documentation

如果您仅在prop更改时使用componentWillReceiveProps重新计算某些数据,请使用memoization helper。

这是指你在componentWillReceiveProps内部检查是为了避免不必要地多次重新计算同样的事情。在linked blog post中,它建议缓存昂贵函数的结果,以便可以查找,而不是重新计算。这可以使用诸如memoize-one之类的帮助器来完成。

如果你在支柱改变时使用componentWillReceiveProps“重置”一些状态,可以考虑使用一个键完全控制或完全不受控制。

同样,linked blog post更详细地描述了这一点,但简而言之:

  • “完全受控”组件是指没有状态的功能组件(父组件负责处理状态)。
  • “完全不受控制”的替代方案是仅使用props来设置初始状态,然后忽略对道具的所有进一步更改。

在极少数情况下,您可能希望将getDerivedStateFromProps生命周期作为最后的手段。

此函数接收(props, state)并在调用render之前返回对状态的任何更改,使您可以控制执行任何操作。


Original answer, for older versions of React

在这个lifecycle method被调用的时间点,this.props指的是前一组道具。

要比较新道具上的单个属性foo与旧道具上的相同属性,您可以将newProps.foothis.props.foo进行比较。所以在你的例子中:

componentWillReceiveProps (newProps) {
  if( newProps.profileImage !== this.props.profileImage ) /* do stuff */
}

8
投票

您还可以遍历所有道具以查看更改的内容。

componentWillReceiveProps(nextProps) {
  for (const index in nextProps) {
    if (nextProps[index] !== this.props[index]) {
      console.log(index, this.props[index], '-->', nextProps[index]);
    }
  }
}

8
投票

由于React 16.3,不建议使用componentWillReceiveProps,请参阅react网站上的unsafe_componentwillreceiveprops文档。

使用getDerivedStateFromProps代替:

static getDerivedStateFromProps(nextProps, prevState) {
  if(nextProps.profileImage !== prevState.profileImage ) {
    return {stateFoo: 'valueBar'};
  }
}

返回值的行为与setState类似。


3
投票

您仍然可以与this.props.profileImage进行比较,因为直到调用componentWilReceiveProps之后它才会更新。例如,在docs中,使用此示例:

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

0
投票

是的,您可以检查特定道具是否已更改。 this.props在他们改变之前指的是道具。例如:

componentWillReceiveProps(newProps) {
  if( newProps.profileImage != this.props.profileImage ) {
    /* do stuff */
  }
}

注意:每次调用方法时道具都不一定会改变,因此值得测试看看哪个道具发生了变化。


0
投票

就像将来发现这一点的人一样。看来componentWillReceiveProps()将被弃用。文档现在建议您使用getDerivedStateFromProps()。关于为什么可以在这里找到解释:https://reactjs.org/blog/2018/03/29/react-v-16-3.html#component-lifecycle-changes

© www.soinside.com 2019 - 2024. All rights reserved.