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?
To create a deep copy of an object in React, install and use the lodash. clonedeep package. The cloneDeep method recursively clones a value and returns the result. Copied!
To remove the duplicates from an array in React, pass the array to the Set constructor, e.g. [... new Set(arr)] . Each value in a Set has to be unique, so any duplicates get automatically removed.
In React, the state is immutable. In simple terms it means that you should not modify it directly. Instead a new object should be created to set the state using setState .
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
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