redux中dispatch只能是object对象,这对于同步的操作是可行的,但如果是异步的操作,那么将行不通,对此,redux提供了applyMiddleware来增强相应的disptch方法,同时将applyMiddleware返回的函数作为参数传入createStore中,替换当前store中的dispatch方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 default  function  applyMiddleware (...middlewares )  return  createStore => (...args) => { const  store = createStore(...args)throw  new  Error(while  constructing your middleware is  not allowed. ` +this  dispatch.`const  middlewareAPI = {   const  chain = middlewares.map(middleware => middleware(middlewareAPI))return  {
1 2 3 4 5 6 7 8 9 10 11 12 13 //  redux-thunk源码function  createThunkMiddleware(extraArgument) {next  => action => {// next 是store上的dispatch方法if  (typeof action === 'function' ) { // 如果action返回的是function 则继续将dispatch方法往下传,直到action非function 类型// 如果action为非function 类型,则调用store.dispatch方法next (action);
1 2 3 4 5 6 7 8 9 10 11 12 function  createStore(reducer , preloadedState , enhancer )  {  ...    if  (typeof enhancer !== 'undefined') {if  (typeof enhancer !== 'function ') {new  Error('Expected the  enhancer  to  be  a  function .') 
通过applyMiddleware传入中间件增强了dispatch方法,并返回增强的dispatch和其他的createStore上的方法。