在 React 的 setState 函数中更改深场的最佳方法是什么?



假设组件的状态如下:

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

我想换a.b.c。我听说在React中,我们应该用不可变的对象来改变状态。因此,我可能应该克隆state.a的对象,更改c字段并将其传递给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 })

那么,最好的方法是什么呢?我是React的新手。在Vue,我们只要改变它,每件事都会发生。我不知道React的原理。

你的方法是正确的,我通常这样做。。。。

const newA =  {...this.state.a};
newA.b.c = 5;
this.setState({a:newA});

相关内容

最新更新