![](/img/trans.png)
[英]Comparing prevProps and nextProps in a React.memo Component to prevent unnecessary re-rendering but it's acting funny
[英]How to check if prevProps and nextProps are the same in React?
我有这样的生命周期钩子
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (prevProps.activeItems !== this.props.activeItems) {
this.props.doAction();
}
}
和道具有这样的结构
[
{id:1, hidden: true},
{id:2, hidden: false}
{id:3, hidden: true}
]
我需要检查隐藏的属性是否与prev中的相同,以及每个对象中的下一个道具,因此我将知道是否需要在条件或不运行时运行函数。 我怎样才能做到这一点?
不要使用componentWillReceiveProps - 这个钩子很快就会被弃用。 componentDidUpdate是您需要的正确钩子。
问题是您正在进行的比较是浅层比较 - 即它不会比较相应数组中的嵌套值。
基本的想法是你应该遍历两个数组并比较各个嵌套值 - 这里有更多关于它的信息: 如何在JavaScript中比较数组?
您还可以使用类似lodash的isEqual方法在两个数组之间进行深度比较: https ://lodash.com/docs/4.17.10#isEqual
使用componentWillReceiveProps。
componentWillReceiveProps (nextProps) {
if(nextProps.something !== this.props.soemthing) {
//write your statements
}
}
如果你有对象数组,那么你需要通过比较旧的道具来映射数组中的每个对象。
只有在activeItems
元素发生更改的情况下,父组件才能处理此问题以提供不可变的activeItems
。
否则,如果activeItems
数组非常相等,则需要对它们进行测试,例如recompose
:
import { shallowEqual } from 'recompose';
...
componentDidUpdate(prevProps) {
if (shallowEqual(prevProps.activeItems, this.props.activeItems)) {
this.props.doAction();
}
}
你现在可以使用componentWillReceiveProps。 因为它很快就会被弃用
componentWillReceiveProps (nextProps) {
if(nextProps.something === this.props.soemthing) {
// do your work
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.