为什么我的 Redux reducer 认为我的状态是未定义的?

Why does my Redux reducer think my state is undefined?

我相信我几乎是逐行复制 Todo 教程,我收到了这个错误:

Error: Reducer "addReport" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.

这是我的 addReport reducer:

const addReport = (state = [], action) =>
{
  console.log(state)
  switch (action.type) {
    case ADD_NEW_REPORT:
    return [...state,
      addReports(undefined, action)
    ]
    }
}

我添加了日志记录语句并且可以验证它 returns 是一个空数组。即使将状态设置为 1 之类的值也会产生相同的结果。我错过了什么?

您缺少开关盒的 default

default: {
  return {
    ...state
  }
}

如果你忘记了,Redux 就不会像个好孩子一样玩!

或者,您可以在初始状态末尾显式 return: If the state passed to the reducer is undefined, you must explicitly return the initial state.