1. 程式人生 > >redux的combineReducers簡單實現

redux的combineReducers簡單實現

combineReducers簡單封裝

const combineReducers = reducers => {
  return (state = {}, action) => {
    return Object.keys(reducers).reduce(
      (nextState, key) => {
        nextState[key] = reducers[key](state[key], action);
        return nextState;
      },
      {} 
    );
  };
};

//分步解析
function(reducers){}() //執行輸出 傳入reducers

function(state, action){}() //執行輸出 傳入state action

const reducerArr = Object.keys(reducers) //得到reducer陣列(key值陣列)

reducerArr.reduce(fn,{}) //執行reduce函式

function fn(nextState, key){  //這裡的nextState是一個通過引數方式新定義的變數,首次初始化指向reduce的第二個引數{},執行過後返回的值作為第二次fn的入參

  nextState[key] = reducers[key](state[key], action);//儲存接收action和舊state後生成的新的state
  return nextState;
}

使用,分為直接使用和別名使用:

import { combineReducers } from 'redux';
//直接使用
const chatReducer = combineReducers({
  chatLog,
  statusMessage,
  userName
})
//別名使用
const reducer = combineReducers({
  a: doSomethingWithA,
  b: processB,
  c: c
})