2016-12-14 63 views
2

我正在閱讀applyMiddleware的源代碼,並在一些分頁中,他們稱這種方式爲applyMiddleware(...middleware)。那麼next參數何時通過?applyMiddleware()中的next是什麼?

export default function applyMiddleware(...middlewares) { 
    return (next) => 
    (reducer, initialState) => { 
     var store = next(reducer, initialState); 
     var dispatch = store.dispatch; 
     var chain = []; 

     var middlewareAPI = { 
      getState: store.getState, 
      dispatch: (action) => dispatch(action) 
     }; 

     chain = middlewares.map(middleware => middleware(middlewareAPI)); 

     dispatch = compose(...chain, store.dispatch); 
     return { 
      ...store, 
      dispatch 
     }; 
    }; 
} 
+0

你有讀過[**'applyMiddleware' **](http://redux.js.org/docs/api/applyMiddleware.html)文檔嗎? –

回答

0

每個middlewaremiddlewares具有常規格式:

// condensed, does not do anything, just calls the next middleware 
function middleware({ getState }) => (next) => (action) => next(action) 

or 

// expanded, does not do anything, just calls the next middleware 
function middleware({ getState }) { 
    return function (next) { 
    return function (action) { 
     return next(action) 
    } 
    } 
} 

中間件是返回一個函數返回一個函數調用的下一個中間件應該有任何的功能。

要回答你的問題,next作爲參數傳遞給第二個函數。這樣,applyMiddleware存儲增強器可以調用鏈中的下一個中間件。中間件語法有點令人困惑(來自docs):

中間件的聲音聽起來要比實際複雜得多。真正瞭解中間件的唯一方法是看看現有的中間件是如何工作的,並嘗試編寫自己的。功能嵌套可能會令人生畏,但大多數中間件實際上都是10行內存,並且嵌套和可組合性使得中間件系統功能強大。

相關問題