I am now using shouldComponentUpdate
but I cannot simply do prevProps.myPropObj == this.state.props.myPropObj
to compare. It is an object and I would need to do deep compare. Does react expose to me some method to tell me if my prop changed or not? Or do they expect me to do the deep comparison myself? I was thinking react specializes in this comparison so it should tell us true/false on if same or not no?
If the props are immutable, you can use react's shallowCompare
. The props can be immutable if you use something like immutablejs, or you change the objects by replacing and not mutating them, for example const prop = Object.assign({}, prop, { changedValues: 'value' });
var shallowCompare = require('react-addons-shallow-compare');
export class SampleComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
render() {
return <div className={this.props.className}>foo</div>;
}
}
For non-es6, non-node environment:
The equivalent of var shallowCompare = require('react-addons-shallow-compare');
is var shallowCompare = React.addons.shallowCompare;
so complete example would be:
var SampleComponent = React.createClass({
shouldComponentUpdate: function(nextProps, nextState) {
return React.addons.shallowCompare(this, nextProps, nextState);
},
render: function() {
return React.createElement('div', {className:this.props.className}, 'foo');
}
});
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