如何在动态对象中的数组中 add/remove

How to add/remove in Array inside dynamic Object

我有一个具有这种结构的减速器:

{
  [key]: {
    answers: [
      { key: 1, mode: 'INCLUDE' }
    ],
    period: {},
  }
}

现在我想将项目添加到 answers-array,但这不起作用(在 reducer 内)。因为每次都会替换唯一的现有数组项。

return {
  ...state,
  [action.payload.serieId]: {
    ...state[action.payload.serieId],
    answers: [
      { ...action.payload.answerFilter },
    ],
  },
}

这也行不通,因为找不到 属性 ...状态 [action.payload.serieId]. 答案。

return {
  ...state, [action.payload.serieId]: 
  {
    ...state[action.payload.serieId],
    answers: [ 
      ...state[action.payload.serieId].answers
      { ...action.payload.answerFilter },
    ],
  },
}

错误:

TypeError: Cannot convert undefined or null to object

有什么方法可以在 reducer 内部解决这个问题,还是我必须在外部修改整个数组,然后在每次更改时简单地设置它的整体?

"Answers" 是一个数组,因为其中可能有多个过滤器。

如果 serieId 没有进入 reducer 状态,你需要应用一个默认值,所以如果你做类似

的事情应该会有用
const currentSerie = state[action.payload.serieId] || generateStateFromScratch();

然后你可以做类似的事情

return {
  ...state,
  [action.payload.serieId]: {
    ...currentSerie,
    ...{
      answers: [ ...currentSerie.answers, { ...action.payload.answerFilter } ]
    }
  }
}

所以你 generateStateFromScratch 函数应该看起来像这样

const generateStateFromScratch = () => ({
    answers: [
      { key: 1, mode: 'INCLUDE' }
    ],
    period: {}
})

You can return an empty answers array into the initial state if needed.