使用不变性帮助器更新处于 React 状态的数组对象
Updating the array object in React state using immutability helper
我正在使用 immutability helper.
更新处于 React 状态的数组中的对象
我要修改的对象是嵌套的:
this.state = {
a: {
b: [{ c: '', d: ''}, ...]
}
}
我想使用不变性助手更新 b 的第 n 个元素中的属性 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 });
我知道上面的代码有点难看。我假设使用不变性助手的代码将解决我的问题。谢谢
我正在从此处的不变性助手导入 update
:)
this.state = {
a: {
b: [{ c: '', d: ''}, ...]
}
}
this.setState((prevState, props) => update(prevState, {
a: {
b: {
$apply: b => b.map((item, ii) => {
if(ii !== n) return item;
return {
...item,
c: 'new value'
}
})
}
}
}))
一种方法是使用 $set
let index = 0;
let newState = update(this.state, {
a: {
b: {
[index]: {
c: { $set: "new value"}
}
}
}
});
this.setState(newState);
我正在使用 immutability helper.
更新处于 React 状态的数组中的对象我要修改的对象是嵌套的:
this.state = {
a: {
b: [{ c: '', d: ''}, ...]
}
}
我想使用不变性助手更新 b 的第 n 个元素中的属性 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 });
我知道上面的代码有点难看。我假设使用不变性助手的代码将解决我的问题。谢谢
我正在从此处的不变性助手导入 update
:)
this.state = {
a: {
b: [{ c: '', d: ''}, ...]
}
}
this.setState((prevState, props) => update(prevState, {
a: {
b: {
$apply: b => b.map((item, ii) => {
if(ii !== n) return item;
return {
...item,
c: 'new value'
}
})
}
}
}))
一种方法是使用 $set
let index = 0;
let newState = update(this.state, {
a: {
b: {
[index]: {
c: { $set: "new value"}
}
}
}
});
this.setState(newState);