小编典典

使用不变性助手在React状态下更新数组对象

reactjs

我正在使用不变性助手在React状态下更新数组中的对象。

我要修改的对象是嵌套的:

this.state = {
  a: {
    b: [{ c: '', d: ''}, ...]
  }
}

我想使用不变性助手来更新b的第n个元素内的prop c。

没有不变性帮助器的等效代码是:

const newState = Object.assign({}, this.state);
newState.a = Object.assign({}, newState.a);
newState.a.b = newState.a.b.slice();
newState.a.b[n] = Object.assign({}, newState.a.b[n]);
newState.a.b[n].c = 'new value';
this.setState({ newState });

我知道上面的代码有点难看。我假设使用不变性助手的代码可以解决我的问题。谢谢


阅读 218

收藏
2020-07-22

共1个答案

小编典典

一种方法是使用 $set

let index = 0;
let newState = update(this.state, {
   a: {
     b: {
      [index]: {
               c: { $set: "new value"}
       }
    }
  }
});
this.setState(newState);

jsfiddle

2020-07-22