Why does my Redux reducer think my state is undefined?

╄→尐↘猪︶ㄣ 提交于 2019-12-01 00:39:47

问题


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

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.

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)
    ]
    }
}

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?


回答1:


You are missing the default of the switch case.

default: {
  return {
    ...state
  }
}

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

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.



来源:https://stackoverflow.com/questions/38015896/why-does-my-redux-reducer-think-my-state-is-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!