Sandbox example:
https://codesandbox.io/s/207ml94zj0
The offending bit of code:
handleChange(e) {
console.log(e.target.value);
console.log("state before", this.state);
let a = this.state.tranches.slice(); //Clone the state
a[0].start = e.target.value;
a[0].end = 5;
console.log("state after", this.state);
this.setState({ tranches: a });
}
If I just reproduce this as some pure javascript:
const state = {
tranches: [{
start: "foo",
end: 1
}]
}
const value = "bar";
console.log("state before", state);
let a = state.tranches.slice(); //Clone the state
a[0].start = value;
a[0].end = 5;
console.log("state after", state);
We can see that the value of state
is mutated between state before
and state after
.
Yet in the sandbox example - that isn't the case.
And actually, what's happening is what's being printed to the console in the React example, is the value of the state after the code has run.
Why is that the case?