我在redux(redux@3.7.2)中使用combineReducer方法时遇到错误。当我只使用一个reducer时,相同的代码将起作用。
代码
const { createStore, combineReducers, applyMiddleware } = require ('redux')
const aReducer = (state, action) => {
switch (action.type) {
case 'A':
{
return { ...state };
}
default: return state;
}
return state;
}
const bReducer = (state, action) => {
switch (action.type) {
case 'B':
{
return { ...state };
}
default: return state;
}
return state;
}
const configureStore = (initialState) => {
let rootReducer = combineReducers({ a:aReducer, b:bReducer });
console.log('configureStore', initialState);
const str = createStore(rootReducer, initialState);
return str;
};
const store = configureStore({});
console.log('store',store);
store.subscribe(() => {
console.log(store.getState());
});
在创建商店行中,如果我将rootReducer替换为aReducer,则此代码不会有任何问题。我不明白为什么减速器返回未定义状态,我将初始状态作为平面对象传递。
答案 0 :(得分:1)
这里有两件事。首先,combineReducers
还将对象中每个reducer的状态与参数reducers对象的键相同,因此要正确初始化每个状态,您需要:
const store = configureStore({a: {}, b: {}});
这还不足以解决问题,因为combineReducers
还要求每个reducer都可以处理状态undefined
并且永远不会返回undefined
(see the docs)。如果它不能收到此错误:
Error: Reducer "..." 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.
关于这一点的令人困惑的事情是,在调用combineReducers
时(即在状态初始化之前)完成检查,但是在使用reducer之前不会显示错误。这意味着即使您正确初始化状态,并且您的Reducer也永远不会收到状态undefined
,如果Reducer无法处理它,您仍然会收到错误。
要解决此问题,请将每个reducer中的(state, action) => {
替换为(state = {}, action) => {
,如果null
为state
,则明确返回undefined
。请注意,这些初始状态仅在您未将初始状态传递给createStore
时使用。为了避免混淆,我通常在reducers中进行所有初始化,而不是createStore
。