React state changes when its assigned variable changes
The state changes because your variable a
holds a reference to testState
. This is a no-op. You should never change it directly and only use the setState
function provided by react.
this.setState({ testState: { testValue: "Debugging is awesome" } });
If you don't want to change the state you can use the spread operator:
let a = { ...this.state.testState };
Why does it act this way?
It's because objects
and arrays
in JavaScript are reference values. Wherever you update its value, it also updates the source. In this case, you'd want to make it immutable. You would do that by assigning a new object. In ES6 this can be done with the spread operator
.
Solution
let a = { ...this.state.testState };
Further reading
- Mozilla Web Docs: Spread syntax
You have to deep copy the state if you don't want it to be effected (Object.assign):
this.state={
testState: { testValue: "Test State" }
}
testFn = () => {
let a;
a = Object.assign({}, this.state.testState);
a.testValue = "Debugging is awesome";
console.log(this.state.testState)
}
Or you can use {...this.state.testState}
instead of Object.assign
Note that using the spread operator {...}
will not keep the prototype property (instanceof
).