我正在使用 immutability helper 更新处于 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 });
我知道上面的代码有点难看。我假设使用不变性助手的代码将解决我的问题。谢谢
最佳答案
一种方法是使用 $set
let index = 0;
let newState = update(this.state, {
a: {
b: {
[index]: {
c: { $set: "new value"}
}
}
}
});
this.setState(newState);
关于javascript - 使用不变性助手更新 React 状态下的数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40276907/