I was wondering if this sort of code would cause side effects.
Let's say I have some state object in a component that contains an array which itself contains objects with various properties:
getInitialState: function () {
return {
willContainObjects: [];
}
Now, I have a function which will edit that object and then create a new state object:
editObjectInArray: function (index) {
var obj= this.state.willContainObjects[index];
obj.someProp = 3; // mutating this.state!!!
this.setState({
willContainObjects: this.state.willContainObjects.slice(0, index)
.concat(details)
.concat(this.state.willContainObjects.slice(index+1))
}); // end setState
},
obj.someProp = 3 mutated the state of this.state directly, but right before calling this.setState and causing re-render. Will this direct mutation of state before calling setState have any unintended side-effects? I know React recommends not to do this but I think this is an exception. I could use Object.assign to create a new object instead of mutating, but I don't see a point of doing this in this case.
The only "side-effect" will be that any components that use the PureRenderMixin or implement a shouldComponentUpdate method that uses a shallow equality test may not understand that the object has really changed.
Other than that, though not recommended, it should work OK.
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