为什么我的 Redux 减速器认为我的状态是未定义的? [英] Why does my Redux reducer think my state is undefined?

查看:44
本文介绍了为什么我的 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.

这篇关于为什么我的 Redux 减速器认为我的状态是未定义的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆