Redux源碼(五) —— combineReducers.js

Source Time

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
  }
}
複製代碼

Analysis

combineReducers接受一個reducers對象,並返回一個combination統一處理dispatch觸發的action操做。在combineReducers中會進行過濾無效reducer、處理reducer返回undefined無效結果等狀況,最終獲得一個包含了有效子reducer的finalReducer對象以及由此衍生獲得的finalReducerKeys數組。javascript

在新的能夠理解爲rootReducer——combination中,會根據finalReducerKeys數組遍歷finalReducer對象,對每個可能存在的子reducer都運行一次獲取到對應的nextStateForKey值,最後合併到nextState上,而每一次獲得的新nextStateForKey都會與以前的previousStateForKey比較,用於判斷combination是直接返回原始state仍是返回新獲得的nextStatejava

Example

爲了方便理解,能夠看個簡單的例子數組

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}
複製代碼

All

相關文章
相關標籤/搜索