我的理解是,react 使用严格的相等性检查,所以如果你使用使用不可变状态的 redux,相等性检查是否每次都会失败?
例如,我在阅读的一篇文章中看到了以下代码片段:
componentDidUpdate(prevProps) {
//Typical usage, don't forget to compare the props
if (this.props.user !== prevProps.user) {
this.fetchData(this.props.user.userName);
}
}
如果传入的 props 对象来自 redux 并且用户属性是一个对象或数组,它将有一个不同的引用,并且每次检查都会失败。
这是正确的吗?
如果是这种情况,React Redux 优化组件是否会重新渲染我手动深度检查从 HOC 中的 mapStateToProps 返回的对象值?或者这也总是会失败?谢谢
最佳答案
您只能对原始值进行严格相等,而不能对对象进行严格相等。
所以你应该按如下方式定义函数:
function isEquivalent(a, b) {
// Create arrays of property names
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
// If number of properties is different,
// objects are not equivalent
if (aProps.length != bProps.length) {
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
return false;
}
}
// If we made it this far, objects
// are considered equivalent
return true;
}
或者您可以使用 lodash 函数:
_.isEqual(object1, object2)
关于javascript - React如何在生命周期方法中处理对象严格相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57550414/