有没有一种方法可以检查里面的道具发生了变化(没有在其他地方存储旧道具)componentWillReceiveProps?
componentWillReceiveProps
即
componentWillReceiveProps (newProps) { if( /* newProps.profileImage is different to previous props */ ) /* do stuff */ }
请注意,该功能componentWillReceiveProps现已 弃用 。引用官方文件:
如果componentWillReceiveProps仅当属性更改时才用于重新计算某些数据,请改用备忘录助手。
这是指您的内部检查componentWillReceiveProps避免不必要地多次重新计算相同内容的情况。在链接的博客文章中,它建议将昂贵功能的结果缓存起来,以便可以查找它,而不是重新计算它。可以使用诸如memoize- one之类的助手来完成。
如果您过去componentWillReceiveProps在道具更改时“重置”某些状态,请考虑使用键使组件完全受控或完全不受控制。
同样,链接的博客文章对此进行了更详细的描述,但简而言之:
props
在极少数情况下,您可能希望将getDerivedStateFromProps 生命周期作为最后的手段。
getDerivedStateFromProps
该函数接收(props, state)并返回render调用前状态的任何更改,使您可以执行所需的操作。
(props, state)
render
在此生命周期方法被调用的时间点上,this.props是指先前的一组道具。
this.props
要将foo新道具的单个属性与旧道具的相同属性进行比较newProps.foo,只需与比较即可this.props.foo。因此,在您的示例中:
foo
newProps.foo
this.props.foo
componentWillReceiveProps (newProps) { if( newProps.profileImage !== this.props.profileImage ) /* do stuff */ }