如何检查 componentWillReceiveProps 中更改了哪些props

IT技术 reactjs
2021-04-27 01:52:13

有没有办法检查里面有哪些props发生了变化(不将旧props存储在其他地方)componentWillReceiveProps

IE

componentWillReceiveProps (newProps) {
  if( /* newProps.profileImage is different to previous props */ ) /* do stuff */
}
4个回答

请注意,该功能componentWillReceiveProps现已弃用引用官方文档

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

这是指你的检查里面的情况componentWillReceiveProps是为了避免多次不必要地重新计算相同的事情。链接的博客文章中,它建议缓存昂贵函数的结果,以便可以查找,而不是重新计算。这可以使用诸如memoize-one 之类的助手来完成

如果您曾经componentWillReceiveProps在 prop 更改时“重置”某些状态,请考虑使用键使组件完全受控或完全不受控制。

同样,链接的博客文章更详细地描述了这一点,但简而言之:

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

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

此函数接收(props, state)并返回对render调用之前状态的任何更改,让您可以控制做任何您想做的事情。


原始答案,适用于旧版本的 React

调用这个生命周期方法的时间点this.props指的是之前的一组 props。

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

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

您还可以遍历所有props以查看发生了什么变化。

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

从 React 16.3 开始,不推荐使用 componentWillReceiveProps,请参考react 官unsafe_componentwillreceiveprops文档。

使用getDerivedStateFromProps来代替:

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

返回值的行为与 类似setState

您仍然可以与 进行比较this.props.profileImage,因为它在componentWilReceiveProps被调用之前不会更新例如,在docs 中,使用了这个例子:

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