为什么我的 Redux 减速器认为我的状态是未定义的?

为什么我的 Redux 减速器认为我的状态是未定义的?

问题描述:

我相信我正在逐行复制 Todo 教程,但出现此错误:

I believe I'm copying the Todo tutorial pretty much line for line, I am getting this error:

错误:ReduceraddReport"在初始化期间返回未定义.如果传递给 reducer 的状态未定义,则必须显式返回初始状态.初始状态可能不是未定义的.

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 减速器:

And here is my addReport reducer:

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

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

I added the logging statement and can verify that it returns an empty array. Even setting state to something like 1 will produce the same results. What am I missing?

您缺少 switch case 的 default.

You are missing the default of the switch case.

default: {
  return {
    ...state
  }
}

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

Redux won't play along like a nice kid if you forget to do it!

或者,您可以在最后明确返回初始状态:如果传递给reducer的状态未定义,则必须显式返回初始状态.

Or alternatively, you can explicitly return at the end the initial state: If the state passed to the reducer is undefined, you must explicitly return the initial state.