跳到主内容

Uncaught Error: Reducer "xxx" returned undefined during initialization

· 2分钟阅读

问题

React 引入了 redux 后,自定义 reducer 函数时,代码如下

export default function myReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_USER:
return { ...state, ...action.payload };
}
}

结果运行项目时候报错了,Uncaught Error: Reducer "xxx" 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. If you don't want to set a value for this reducer, you can use null instead of undefined.

原因

通过报错信息可以得知,reducer 在初始化时候返回了 undefined

于是进行了代码调试,combineReducers 函数里面,有一个方法,assertReducerShape。这里就是抛出错误的位置。

function assertReducerShape(reducers) {
Object.keys(reducers).forEach((key) => {
const reducer = reducers[key];
const initialState = reducer(undefined, { type: ActionTypes.INIT });
if (typeof initialState === "undefined") {
throw new Error(
`Reducer "${key}" 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. If you don't want to set a value for this reducer, ` +
`you can use null instead of undefined.`
);
}
});
}

解决

解决方法也很简单,只需要在定义 reducer 的时候,需要在 switch 里面加入 default 条件,让其不返回 undefined

export default function myReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_USER:
return { ...state, ...action.payload };
default:
return state;
}
}