Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  39] [ 2]  / answers: 1 / hits: 36511  / 6 Years ago, fri, july 20, 2018, 12:00:00

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?


More From » reactjs

 Answers
123

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




[#53926] Tuesday, July 17, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleyv

Total Points: 259
Total Questions: 99
Total Answers: 107

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;