When I want to copy the state like this:
let copy = this.state.foo
copy.push('bar')
the state copied correctly, but with its reference, and when I change 'copy' the main state changes.
What should I do to avoid this change?
When I want to copy the state like this:
let copy = this.state.foo
copy.push('bar')
the state copied correctly, but with its reference, and when I change 'copy' the main state changes.
What should I do to avoid this change?
You can use array spread or Array.concat()
to make a shallow clone, and add new items as well):
const state = {
foo: ['bar']
};
const copy = [...state.foo, 'bar'];
console.log(copy === state.foo); // false