有没有办法检查里面有哪些props发生了变化(不将旧props存储在其他地方)componentWillReceiveProps
?
IE
componentWillReceiveProps (newProps) {
if( /* newProps.profileImage is different to previous props */ ) /* do stuff */
}
有没有办法检查里面有哪些props发生了变化(不将旧props存储在其他地方)componentWillReceiveProps
?
IE
componentWillReceiveProps (newProps) {
if( /* newProps.profileImage is different to previous props */ ) /* do stuff */
}
请注意,该功能componentWillReceiveProps
现已弃用。引用官方文档:
如果您用于
componentWillReceiveProps
仅在 prop 更改时重新计算某些数据,请改用 memoization helper。
这是指你的检查里面的情况componentWillReceiveProps
是为了避免多次不必要地重新计算相同的事情。在链接的博客文章中,它建议缓存昂贵函数的结果,以便可以查找,而不是重新计算。这可以使用诸如memoize-one 之类的助手来完成。
如果您曾经
componentWillReceiveProps
在 prop 更改时“重置”某些状态,请考虑使用键使组件完全受控或完全不受控制。
同样,链接的博客文章更详细地描述了这一点,但简而言之:
props
来设置初始状态,然后忽略对props的所有进一步更改。在极少数情况下,您可能希望将
getDerivedStateFromProps
生命周期用作最后的手段。
此函数接收(props, state)
并返回对render
调用之前状态的任何更改,让您可以控制做任何您想做的事情。
在调用这个生命周期方法的时间点,this.props
指的是之前的一组 props。
要将foo
新props上的单个属性与旧props上的相同属性进行比较,您只需newProps.foo
与this.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
});
}