I want to check all properties and state if they are changed, return true if any changed and make a base component for all my root components.
I'm wondering if it won't be the best practice and make my components slow. Also, what I did always returns true:
shouldComponentUpdate: function(newProps, newState) {
if (newState == this.state && this.props == newProps) {
console.log('false');
return false;
}
console.log('true');
return true;
},
It is considered best practice to compare props and state in shouldComponentUpdate
to determine whether or not you should re-render your component.
As for why it's always evaluating to true, I believe your if statement isn't performing a deep object comparison and is registering your previous and current props and state as different objects.
I don't know why you want to check every field in both objects anyway because React won't even try to re-render the component if the props or state hasn't changed so the very fact the shouldComponentUpdate
method was called means something MUST have changed. shouldComponentUpdate
is much better implemented to check maybe a few props or state for changes and decide whether to re-render based on that.
I think there's a problem in most of the tutorials I've seen (including the official docs) in the way that stores are accessed. Usually what I see is something like this:
// MyStore.js
var _data = {};
var MyStore = merge(EventEmitter.prototype, {
get: function() {
return _data;
},
...
});
When I used this pattern, I found that the newProps
and newState
in functions like shouldComponentUpdate
always evaluate as equal to this.props and this.state. I think the reason is that the store is returning a direct reference to its mutable _data
object.
In my case the problem was solved by returning a copy of _data
rather than the object itself, like so:
get: function() {
return JSON.parse(JSON.stringify(_data));
},
So I'd say check your stores and make sure you're not returning any direct references to their private data object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With