0

Say a component's state is as follows:

{
  a: { b: {c: 1, d: 1 }}
}

I want to change a.b.c. I heard that in React we should immutable object to change state. So may be i should clone the object of state.a, change the c field and pass it to setState:

const newA = JSON.parse(JSON.stringify(this.state.a)); // could use other clone method, just for example
newA.b.c = 5 // change
this.setState({ a: newA })

So what is the best way to do this? I am new to React. In Vue, we just change it and every thing happens. I don't know React's principle.

tomwang1013
  • 1,349
  • 2
  • 13
  • 27

1 Answers1

0

Your approach is correct and I usually do this....

const newA =  {...this.state.a};
newA.b.c = 5;
this.setState({a:newA});
Anil Kumar
  • 2,223
  • 2
  • 17
  • 22
  • But we need a deep clone, not a shadow on buy `{ ...obj }`。But a deep clone is heavy, so are there other method to do it? – tomwang1013 Dec 07 '18 at 05:50