Reactjs:在修改对象之前,是否需要复制处于组件状态的对象

Reactjs: Is it necessary to copy object in component state before modifying it?

本文关键字:对象 于组件 组件 状态 复制 修改 Reactjs 是否      更新时间:2023-09-26

假设我的reactjs组件有两种状态:

a: {
    a: 1
},
b: [1, 2, 3]

现在我希望他们成为:

a: {
    a: 1,
    b: true
},
b: [1, 2, 3, 4]

这样做正确吗:

this.state.a.b = true;
b = this.state.b.push(4);
this.setState({
    a: this.state.a,
    b: b
});

如果没有,合适的方法是什么。

最好的方法。

  this.setState({
    a: Object.assign({}, this.state.a, { b: true }),
    b: [...this.state.b, 4]
  });

状态属性应该被替换,而不是突变:

this.setState({
    a: { // create new a object
        a: this.state.a.a,
        b: true
    },
    b: this.state.b.concat([4]) // create new b array
});

直接从文档:

不直接修改状态

例如,这不会重新渲染组件:

// Wrong
this.state.comment = 'Hello';

相反,请使用setState():

// Correct
this.setState({comment: 'Hello'});


因此,如果您使用setState,则在修改对象之前无需复制它

因此您的代码可能如下所示:

this.setState({
    a: (this.state.a.b = true),
    b: this.state.b.push(4)
})