Redux中間件對閉包的一個巧妙使用

最近在看Redux的源碼,發現Redux在使用中間件applyMiddleware.js的源碼中,有一個對閉包很是巧妙的使用,解決了「雞生蛋,蛋生雞」的問題,特分享給你們。前端

Redux中間件的函數簽名形式以下:json

({dispatch, getState}) => next => action => {
   // 函數體
}

applyMiddleware.js中的函數applyMiddleware(...middlewares)用於根據中間件生成action通過的中間件鏈。先來看一個錯誤版本的實現:redux

/*
 * @param {...Function} middlewares The middleware chain to be applied.
 * @returns {Function} A store enhancer applying the middleware.
 */
export default function applyMiddleware(...middlewares) {
  return (createStore) => (reducer, initialState, enhancer) => {
    var store = createStore(reducer, initialState, enhancer)
    var chain = []

    var middlewareAPI = {
      getState: store.getState,
      dispatch: store.dispatch
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    var dispatch = compose(...chain)(store.dispatch)    //compose(f, g, h) 等價於函數
                                                    //(...args)=>f(g(h(args)))

    return {
      ...store,
      dispatch
    }
  }

核心邏輯是chain = middlewares.map(middleware => middleware(middlewareAPI))dispatch = compose(...chain)(store.dispatch)這兩行。第1句代碼是根據中間件生成一個數組chain,chain的元素是簽名爲next => action => {...}形式的函數,每一個元素就是最終中間件鏈上的一環。第2句代碼利用compose函數,將chain中的函數元素組成一個「洋蔥式」的大函數,chain的每一個函數元素至關於一層洋蔥表皮。Redux發送的每個action都會由外到內依次通過每一層函數的處理。假設有3層函數,從外到內依次是a,b,c,函數的實際調用過程是,a接收到action,在a函數體內會調用b(a的參數next,指向的就是b),並把action傳遞給b,而後b調用c(b的參數next指向的就是c),同時也把action傳遞給c,c的參數next指向的是原始的store.dispatch,所以是action dispatch的最後一環。這樣分析下來,程序是沒有問題的,但當咱們的中間件須要直接使用dispatch函數時,問題就出來了。例如,經常使用於發送異步action的中間件redux-thunk,就須要在異步action中使用dispatch:數組

export function fetchPosts(subreddit) {  
  return function (dispatch) {
    dispatch(requestPosts(subreddit))
    return fetch(`https://www.reddit.com/r/${subreddit}.json`)
      .then(
        response => response.json(),
        error => console.log('An error occured.', error)
      )
      .then(json =>
        dispatch(receivePosts(subreddit, json))
      )
  }
}

fetchPosts使用的dispatch,是redux-thunk傳遞過來的,指向的是middlewareAPI對象中的dispatch,實際等於store.dispatch。當執行dispatch(requestPosts(subreddit))時,這個action直接就到了最後一環節的處理,跳過了redux-thunk中間件以後的其餘中間件的處理,顯然是不合適的。咱們但願的方式是,這個action依然會從最外層的中間件開始,由外到內通過每一層中間件的處理。因此,這裏使用的dispatch函數不能等於store.dispatch,應該等於compose(...chain)(store.dispatch),只有這樣,發送的action才能通過每一層中間件的處理。如今問題出來了,chain = middlewares.map(middleware => middleware(middlewareAPI))須要使用dispatch = compose(...chain)(store.dispatch)返回的dispatch函數,而dispatch = compose(...chain)(store.dispatch)的執行又依賴於chain = middlewares.map(middleware => middleware(middlewareAPI))的執行結果,咱們進入死循環了。閉包

問題的解決方案就是閉包。當咱們定義middlewareAPI的dispatch時,不直接把它指向store.dispatch,而是定義一個新的函數,在函數中引用外部的一個局部變量dispatch,這樣就造成了一個閉包,外部dispatch變量的變化會同步反映到內部函數中。以下所示:app

export default function applyMiddleware(...middlewares) {
  return (createStore) => (reducer, initialState, enhancer) => {
    var store = createStore(reducer, initialState, enhancer)
    var dispatch = store.dispatch;   // 須要有初始值,保證中間件在初始化過程當中也能夠正常使用dispatch
    var chain = []

    var middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)    // 經過閉包引用外部的dispatch變量
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)    //compose(f, g, h) 等價於函數
                                                    //(...args)=>f(g(h(args)))

    return {
      ...store,
      dispatch
    }
  }

這樣,「雞生蛋,蛋生雞」的問題就解決了。若是這個例子對你來講太複雜,能夠用下面這個簡化的例子幫助你理解:異步

const middleware = ({dispatch}) => (next) => (number) => {
  console.log("in middleware");
  if(number !== 0){
    return dispatch(--number);
  }
  
  return next(number);
}

function test() {
  var dispatch = (number) => { 
    console.log("original dispatch");
    return number;
  };
  var middlewareAPI = {
    dispatch
  }
  
  dispatch = middleware(middlewareAPI)(dispatch);
  
  return {
    dispatch
  }
}

var {dispatch} = test();
dispatch(3);

//輸出:
"in middleware"
"original dispatch"

const middleware = ({dispatch}) => (next) => (number) => {
  console.log("in middleware");
  if(number !== 0){
    return dispatch(--number);
  }
  
  return next(number);
}

function test() {
  var dispatch = (number) => { 
    console.log("original dispatch");
    return number;
  };
  var middlewareAPI = {
    dispatch: (number) => {dispatch(number);}
  }
  
  dispatch = middleware(middlewareAPI)(dispatch);
  
  return {
    dispatch
  }
}

var {dispatch} = test();
dispatch(3);

//輸出 
"in middleware"
"in middleware"
"in middleware"
"in middleware"
"original dispatch"

第二種方式,middleware中dispatch的number會再次經歷中間件的處理,當number=3,2,1,0時,都會進入一次middleware函數,當number=0時,next(0)調用的是test中定義的初始dispatch函數,所以再也不通過middleware的處理。函數


歡迎關注個人公衆號:老幹部的大前端,領取21本大前端精選書籍!fetch

3808299627-5a93ba468b59a

相關文章
相關標籤/搜索