使用不变性助手在React状态下更新数组对象 [英] Updating the array object in React state using immutability helper

查看:98
本文介绍了使用不变性助手在React状态下更新数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用不变性帮助器以React状态更新数组中的对象

I am updating an object within an array in React state using immutability helper.

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

The object I want to modify is nested:

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

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

I want to update the prop c within the nth element of b using immutability helper.

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

The equivalent code without the immutability helper is:

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 });

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

I know the above code is a bit ugly. I am assuming the code using immutability helper will solve my problem. Thanks

推荐答案

一种方法是使用$set

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

jsfiddle

这篇关于使用不变性助手在React状态下更新数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆