export default function combineReducers(reducers) {
const reducerKeys = Object.keys(reducers)
const finalReducers = {}
// ... 過濾無效key,有效的添加到finalReducers上
const finalReducerKeys = Object.keys(finalReducers)
// ... 建立異常stateKey緩存對象
// ... 錯誤斷言
return function combination(state = {}, action) {
// ... 有錯誤斷言處理錯誤斷言
// ... 非生產環境獲取異常state警告信息,並彈出警告
let hasChanged = false
const nextState = {}
for (let i = 0; i < finalReducerKeys.length; i++) {
const key = finalReducerKeys[i]
const reducer = finalReducers[key]
const previousStateForKey = state[key]
const nextStateForKey = reducer(previousStateForKey, action)
// ... 處理返回state爲undefined的錯誤信息
nextState[key] = nextStateForKey
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
return hasChanged ? nextState : state
}
}
複製代碼
combineReducers
接受一個reducers
對象,並返回一個combination
統一處理dispatch
觸發的action
操做。在combineReducers
中會進行過濾無效reducer、處理reducer返回undefined無效結果等狀況,最終獲得一個包含了有效子reducer的finalReducer
對象以及由此衍生獲得的finalReducerKeys
數組。javascript
在新的能夠理解爲rootReducer
——combination
中,會根據finalReducerKeys
數組遍歷finalReducer
對象,對每個可能存在的子reducer都運行一次獲取到對應的nextStateForKey
值,最後合併到nextState
上,而每一次獲得的新nextStateForKey
都會與以前的previousStateForKey
比較,用於判斷combination
是直接返回原始state仍是返回新獲得的nextState
。java
爲了方便理解,能夠看個簡單的例子數組
const theDefaultReducer = (state = 0, action) => state;
const firstNamedReducer = (state = 1, action) => state;
const secondNamedReducer = (state = 2, action) => state;
const rootReducer = combineReducers({
theDefaultReducer,
firstNamedReducer,
secondNamedReducer
});
const store = createStore(rootReducer);
console.log(store.getState());
// -> {theDefaultReducer: 0, firstNamedReducer: 1, secondNameReducer: 2}
複製代碼