我正在使用immutability helper更新React状态的数组中的对象.
我想要修改的对象是嵌套的:
this.state = {
a: {
b: [{ c: '', d: ''}, ...]
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用immutability helper更新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 });
Run Code Online (Sandbox Code Playgroud)
我知道上面的代码有点难看.我假设使用immutability helper的代码将解决我的问题.谢谢
我有一个可以分叉的StackBlitz,我找到了类似的答案,但是在将其应用于示例时遇到了麻烦,我认为这是因为我有一组对象。
我的代码可以正常工作,但是它很冗长,我想让使用Redux的其他人更容易理解。
const initialState = [];
const todoReducer = (state, action) => {
switch (action.type) {
case 'ADD_TODO': {
return [...state, {
id: state.length,
name: action.name,
complete: false
}];
}
case 'TOGGLE_COMPLETE': {
let left = state.filter((_, index) => index < action.index)
let right = state.filter((_, index) => index > action.index)
let completed = state.filter((_, index) => index == action.index)
let updatedItem = {
id: completed[0].id,
name: completed[0].name,
complete: !completed[0].complete
}
return [...left, updatedItem, ...right];
}
case 'CLEAR': …Run Code Online (Sandbox Code Playgroud)