简体   繁体   中英

How does react handle object strict equality in lifecycle methods

My understanding is that react uses strict equality checks, so if you are using redux which uses immutable state isn't the equality check going to fail every single time?

For example I saw this code snippet in an article I read:

componentDidUpdate(prevProps) {
//Typical usage, don't forget to compare the props
 if (this.props.user !== prevProps.user) {
   this.fetchData(this.props.user.userName);
 }
}

If the incoming props object is from redux and the user attribute is an object or array it will have a different reference and the check with fail every time.

Is this correct?

And if this is the case does react redux optimize component rerendering my manually deep checking object values that get returned from mapStateToProps in the HOC? Or will that always fail too?

Thanks

You can only do the strict equality to primitive values, not object.

So you should define the function as follows:

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

Or you can use the lodash function:

_.isEqual(object1, object2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM