理解applyMiddleware須要跟createStore結合.首先來看createStore是怎樣建立store的.express
再來看createStore 的源碼redux
createStore的第三個參數enhancer就是applyMiddleware,此時createStore會返回enhancer(createStore)(reducer, preloadedState),也就是createStore在中間件裏面去執行了app
applyMiddleware返回的是函數A(也就是applyMiddleware(...middlewares) =函數A,而後又跑到createStore裏面做爲第三個參數),因此能把createStore做爲參數傳進去異步
一個小例子,測試返回函數後是什麼東西async
import compose from './compose' /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * 建立一個redux store的dispatch方法使用中間件的store加強器. 對於不一樣的人任務,這將會 * 很是方便,好比能夠用很是簡單的方式進行異步操做,或者輸出action的payload * * See `redux-thunk` package as an example of the Redux middleware. *查看`redux-thunk`包做爲一個redux中間件的例子 * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * 由於中間件默認是異步的,這應該是合成鏈中的第一個store加強器 * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. *注意每一箇中間件都會以`dispatch` and `getState`方法做爲參數 * @param {...Function} middlewares The middleware chain to be applied.提供的中間件 * @returns {Function} A store enhancer applying the middleware.store加強器應用的中間件 */ export default function applyMiddleware(...middlewares) { return (createStore) => (reducer, preloadedState, enhancer) => { const store = createStore(reducer, preloadedState, enhancer) let dispatch = store.dispatch let chain = [] const middlewareAPI = { getState: store.getState, dispatch: (action) => dispatch(action) } chain = middlewares.map(middleware => middleware(middlewareAPI)) dispatch = compose(...chain)(store.dispatch) return { ...store, dispatch } } }