React如何在生命周期方法中处理对象严格相等

时间:2019-08-19 04:15:45

标签: javascript reactjs redux react-redux

我的理解是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,并且user属性是对象或数组,则它将具有不同的引用,并且每次检查失败。

这正确吗?

如果是这种情况,是否会对redux优化组件进行重新渲染以重新渲染从HOC中的mapStateToProps返回的手动深度检查对象值?还是那也总是失败?

谢谢

1 个答案:

答案 0 :(得分:1)

您只能对原始值进行严格的相等,而不能对等。

因此,您应该按以下方式定义函数:

pieSeries.labels.template.disabled = true;

或者您可以使用lodash函数:

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;
}