有没有办法检查componentWillReceiveProps
内哪些道具改变了(不在其他地方存放旧道具)?
即
componentWillReceiveProps (newProps) {
if( /* newProps.profileImage is different to previous props */ ) /* do stuff */
}
请注意,函数componenWillReceiveProps
将来会被弃用。引用the official documentation:
如果您仅在prop更改时使用
componentWillReceiveProps
重新计算某些数据,请使用memoization helper。
这是指你在componentWillReceiveProps
内部检查是为了避免不必要地多次重新计算同样的事情。在linked blog post中,它建议缓存昂贵函数的结果,以便可以查找,而不是重新计算。这可以使用诸如memoize-one之类的帮助器来完成。
如果你在支柱改变时使用
componentWillReceiveProps
“重置”一些状态,可以考虑使用一个键完全控制或完全不受控制。
同样,linked blog post更详细地描述了这一点,但简而言之:
props
来设置初始状态,然后忽略对道具的所有进一步更改。在极少数情况下,您可能希望将
getDerivedStateFromProps
生命周期作为最后的手段。
此函数接收(props, state)
并在调用render
之前返回对状态的任何更改,使您可以控制执行任何操作。
在这个lifecycle method被调用的时间点,this.props
指的是前一组道具。
要比较新道具上的单个属性foo
与旧道具上的相同属性,您可以将newProps.foo
与this.props.foo
进行比较。所以在你的例子中:
componentWillReceiveProps (newProps) {
if( newProps.profileImage !== this.props.profileImage ) /* do stuff */
}
您还可以遍历所有道具以查看更改的内容。
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
});
}
是的,您可以检查特定道具是否已更改。 this.props
在他们改变之前指的是道具。例如:
componentWillReceiveProps(newProps) {
if( newProps.profileImage != this.props.profileImage ) {
/* do stuff */
}
}
注意:每次调用方法时道具都不一定会改变,因此值得测试看看哪个道具发生了变化。
就像将来发现这一点的人一样。看来componentWillReceiveProps()将被弃用。文档现在建议您使用getDerivedStateFromProps()。关于为什么可以在这里找到解释:https://reactjs.org/blog/2018/03/29/react-v-16-3.html#component-lifecycle-changes