如何在 redux reducer 中改变状态数组?

How to mutate a array on state in a redux reducer?

更改前的状态如下所示:

foreignBases: [
  {
    base: {
      id: "5b8125ec14bb4f35f8f01aa9",
      ...
    },
    baseuser: {
      userId: "tester1",
      ...
    }
  },
  { base: { ... }, baseuser: { ... } }
]

通过调度,用户将 baseuser 键中的布尔值更改为 true,然后 reducer 应该更新这个特定键值对的状态,但我似乎无法正确处理:

for (let i = 0; i < state.foreignBases.length; i++) {
  if (action.baseUser.created === state.foreignBases[i].baseuser.created) {
    return Object.assign({}, state, {
      foreignBases: [
        ...state.foreignBases,
        {
          base: { ...state.foreignBases[i].base },
          baseuser: action.baseUser
        }
      ]
    });
}

这只是将另一个对象添加到状态,而我真的只需要替换一个对象中的 baseuser 的一个布尔值

请务必查看下方是否有更新。

扩展运算符正在重新插入整个 foreignBases,然后您正在添加另一个对象,我认为这是您的预期突变。

我想你的意思是这样的(未经测试)

for (let i = 0; i < state.foreignBases.length; i++) {
  if (action.baseUser.created === state.foreignBases[i].baseuser.created) {
    let foreignBases = [...state.foreignBases];
    foreignBases[i].baseuser = action.baseUser;
    return Object.assign({}, state, {foreignBases});
  }
}

Update:@devserkan 提醒我传播运算符 "does not do a deep copy",这在 Redux 中是禁忌!所以我去寻找 the updating an item in an array official pattern,我相信它是这样应用的(同样,未经测试):

let foreignBases = state.foreignBases.map((foreignBase) => {
  if (action.baseUser.created === foreignBase.baseuser.created) {
    return {action.baseUser};
  } else {
    return foreignBase
  }
});
return Object.assign({}, state,  { 
   ...foreignBase,
   baseuser: action.baseUser
});

更新 2:评论中的@devserkan 再次贡献了宝贵的见解,这次通过嵌套部分修复了原始的 for 循环状态对象。这类似于突变。这种方法避免了这种情况,并允许您仍然使用 for 循环。

for (let i = 0; i < state.foreignBases.length; i++) {
  if (action.baseUser.created === state.foreignBases[i].baseuser.created) {
    const newItem = {
      ...state.foreignBases[i],
      baseuser: action.baseUser
    };
    const newforeignBases = Object.assign([], state.foreignBases, {
      [i]: newItem
    });
    return Object.assign({}, state, { foreignBases: newforeignBases });
  }
}