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

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3be9b-2c2e7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3be9b-2c2e7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?