Redux 提供了一個combineReducers
方法泛释,用于 Reducer 的拆分。你只要定義各個子 Reducer 函數(shù)耿眉,然后用這個方法蚁袭,將它們合成一個大的 Reducer。
import { combineReducers } from 'redux';
const chatReducer = combineReducers({
chatLog,
statusMessage,
userName
})
export default todoApp;
上面的代碼通過combineReducers方法將三個子 Reducer 合并成一個大的函數(shù)阱当。
這種寫法有一個前提俏扩,就是 State 的屬性名必須與子 Reducer 同名。如果不同名弊添,就要采用下面的寫法录淡。
const reducer = combineReducers({
a: doSomethingWithA,
b: processB,
c: c
})
// 等同于
function reducer(state = {}, action) {
return {
a: doSomethingWithA(state.a, action),
b: processB(state.b, action),
c: c(state.c, action)
}
}
總之,combineReducers()做的就是產(chǎn)生一個整體的 Reducer 函數(shù)油坝。該函數(shù)根據(jù) State 的 key 去執(zhí)行相應(yīng)的子 Reducer嫉戚,并將返回結(jié)果合并成一個大的 State 對象。
下面是combineReducer的簡單實現(xiàn)澈圈。
const combineReducers = reducers => {
return (state = {}, action) => {
return Object.keys(reducers).reduce(
(nextState, key) => {
nextState[key] = reducers[key](state[key], action);
return nextState;
},
{}
);
};
}