First aid! What is the easiest way to make a deep copy of react?

problem description

the data obtained from the background has many layers, but it can only be assigned to the first layer through this.setState . This will not happen if you have requested similar data before. On the one hand, I hope the gods can explain it a little bit, and hope that there can be a quick solution. Thank you very much

...
state = {
  listData: {}
}
...

fetchList({
  ...
})
.then(data => {
    console.log("data ====>", data);
    this.setState({
      listData: Object.assign({}, data);
    }, () => {
     console.log("listData =====>", this.state.listData);
    })
})
The value of

data depth cannot be copied correctly to data

// console.log 1
data =====> {
  x1: xxx,
  x2: {
    x2_1: xxx,
    x2_2: xxx,
  },
  x3: {
    x3_1: xxx,
  }
//...
}

// console.log 2
listData ====> {
 x1: xxx,
 x2: {},
 x3: {},
}

everything at the beginning of the second layer is filtered as empty and cannot be assigned.

May.30,2022

Object.assgin () in

ES6 implements a shallow copy. Deep copy and shallow copy of JS have nothing to do with React.
We are also working on the React project, give two solutions
1, according to the idea of the owner, to achieve a deep copy of Object:

JSON.parse (JSON.stringify (oldObj)); / / none of them is simple and rude. Note that this method ignores the attribute of undefined , but the database generally stores null rather than undefined (the background usually won't help you convert null to undefined , so you may ignore this shortcoming

.

2. There is no need to call copy data. Call setState directly, and React will help you deal with the copied ^ _ ^

.
this.setState({
    listData: data
})

/ / then in any method console.log (this.state.listData)
ends ~!


you can try immutable.js

in any case, deep copying always brings performance problems.
can solve this problem from other angles, such as streamlining data structures

.

there used to be only one state , but now it is split into several. setState updates only one item at a time


let newObj = JSON.parse (JSON.stringify (oldObj))


cdn introduces lodash library, which can save a lot of trouble in development. The deep copy you mentioned can solve

with _ .cloneDeep .
Menu