The objects fetched from the react array will change, which will affect the original array.

define an array

this.state = {
    list: [],
    obj: {}
}
const list = [
    {id: 1},
    {id: 2}
]
this.setState({
    list
})

take out an object

const obj = list[0]
this.setState({
    obj
})

modify the object, modify the value, and then setState

obj.id = 3
this.setState({
    obj
})

here comes the problem. May I ask the reason?

  • if you modify it like this, the obj value in list will also change, and it will look like this
[
    {id: 3},
    {id: 2}
]
  • even if obj and list are cut off, changing the value of obj,list will still change
if you do the following
const list1 = [].concat(list)
const obj = list1[0]
// objlistobj
May.09,2021

this is not the pot of react . js is what it is. The object is a reference type.
you can do this

.
// 
const obj ={...list[0]}
// 
const obj =Object.assign({},list[0])

obj.id = 3
this.setState({
    obj
})

or immutable learn about


learn about the reference to the js object

Menu