9

翻看Redux的源码,可以发现,它主要输出createStore, combineReducers, bindActionCreators, applyMiddleware, compose 五个接口,
首先,让我们先看看middleware是个啥

Redux里我们都知道dispatch一个action,就会到达reducer,而middleware就是允许我们在dispatch action之后,到达reducer之前,搞点事情。

clipboard.png

比如:打印,报错,跟异步API通信等等

下面,让我们一步步来理解下middle是如何实现的:

step 1

假设我们有个需求,想打印出dispatch的action之后,nextState的值。

如图:

clipboard.png

先用一种很简单的方式去实现

let action = toggleTodo('2');
console.log('dispatch', action);
store.dispatch(action);
console.log('next state', store.getState())

Step 2

包裹进函数里

function dispatchAndLoge (store, action) {
    let action = toggleTodo('2');
    console.log('dispatch', action);
    store.dispatch(action);
    console.log('next state', store.getState())
}

但是我们并不想每次要用的时候都需要import这个函数进来,所以我们需要直接替代。

Step 3

直接替代store的dispatch,在原先的dispatch前后加上我们的代码,把原先的store.dispatch放进next里。

const next = store.dispatch;
store.dispatch = function (action) {
   let action = toggleTodo('2');
   console.log('dispatch', action);
   next(action)
   console.log('next state', store.getState())
}

这样下一次我们在用dispatch的时候就自动附带了log的功能,这里的每一个功能,我们都称之为一个middleware,用来增强dispatch的作用。

接下来我们就需要思考,如何可以连接多个middleware。

先把报错的middleware包装成函数写上来

function patchStoreToAddLogging(store) {
  let next = store.dispatch;
  store.dispatch = function dispatchAndLog(action) {
    console.log('dispatching', action);
    let result = next(action);
    console.log('next state', store.getState());
    return result;
  }
}

function patchStoreToAddCrashReporting(store) {
  let next = store.dispatch;
  store.dispatch = function dispatchAndReportErrors(action) {
    try {
      return next(action);
    } catch (err) {
      console.error('Caught an exception!', err);
      Raven.captureException(err, {
        extra: {
          action,
          state: store.getState();
        }
      })
      throw err;
    }
  }
}

这里我们用替代了store.dispatch,其实我们可以直接return 这个函数,就可以在后面实现一个链式调用,赋值这件事就在applyMiddleware里做。

step 4

function logger(store) {
  let next = store.dispatch

  // Previously:
  // store.dispatch = function dispatchAndLog(action) {

  return function dispatchAndLog(action) {
    console.log('dispatching', action)
    let result = next(action)
    console.log('next state', store.getState())
    return result
  }
}

这里我们提供了一个applyMiddleware的方法,可以将这两个middleware连起来
它主要做一件事:

将上一次返回的函数赋值给store.dispatch

function applyMiddlewareByMonkeypatching(store, middlewares) {
  middlewares = middlewares.slice()
  middlewares.reverse()

  // Transform dispatch function with each middleware.
  middlewares.forEach(middleware =>
    // 由于每次middle会直接返回返回函数,然后在这里赋值给store.dispatch,
    、、  下一个middle在一开始的时候,就可以通过store.dispatch拿到上一个dispatch函数
    store.dispatch = middleware(store)
  )
}

接下来,我们就可以这样用

applyMiddlewareByMonkeypatching(store, [logger, crashReporter])

刚刚说过,在applyMiddle里必须要给store.dispatch赋值,否则下一个middleware就拿不到最新的dispatch。

但是有别的方式,那就是在middleware里不直接从store.dipatch里读取next函数,而是将next作为一个参数传入,在applyMiddleware里用的时候把这个参数传下去。

step 5

function logger(store) {
  return function wrapDispatchToAddLogging(next) {
    return function dispatchAndLog(action) {
      console.log('dispatching', action)
      let result = next(action)
      console.log('next state', store.getState())
      return result
    }
  }
}

用es6的柯西化写法,可以写成下面的形式,其实这个next我个人觉得叫previous更为合适,因为它指代的是上一个store.dispatch函数。

const logger = store => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  return result
}

const crashReporter = store => next => action => {
  try {
    return next(action)
  } catch (err) {
    console.error('Caught an exception!', err)
    Raven.captureException(err, {
      extra: {
        action,
        state: store.getState()
      }
    })
    throw err
  }
}

由此我们可以看到所以middleware要传入的参数就是三个,store,next,action。
接下来,再看看redux-thunk 的源码,我们知道,它用于异步API,因为异步API action creator返回的是一个funciton,而不是一个对象,所以redux-thunk做的事情其实很简单,就是看第三个参数action是否是function,是的话,就执行它,如果不是,就按照原来那样执行next(action)

function createThunkMiddleware(extraArgument) {
 return (store) => next => action => {
   if(typeof action === 'function') {
      return action(dispatch, getState, extraArgument)
   }
   return next(action)
 }

}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

step 6

接着,在applyMiddleware里有可以不用立刻对store.dispatch赋值啦,可以直接赋值给一个变量dispatch,作为middleware的参数传递下去,这样就能链式的增强dispatch的功能啦~

function applyMiddleware(store, middlewares) {
  middlewares = middlewares.slice();
  middlewares.reverse();
  let dispatch = store.dispatch;
  middlewares.forEach(middleware => {
    dispatch = middleware(store)(dispatch)
  })
  return Object.assign({}, store, {dispatch})
}

下面终于可以看看applyMiddleware的样子啦

/**
 * Composes single-argument functions from right to left. The rightmost
 * function can take multiple arguments as it provides the signature for
 * the resulting composite function.
 *
 * @param {...Function} funcs The functions to compose.
 * @returns {Function} A function obtained by composing the argument functions
 * from right to left. For example, compose(f, g, h) is identical to doing
 * (...args) => f(g(h(...args))).
 */

export default function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

//可以看出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.
 *
 * See `redux-thunk` package as an example of the Redux middleware.
 *
 * Because middleware is potentially asynchronous, this should be the first
 * store enhancer in the composition chain.
 *
 * Note that each middleware will be given the `dispatch` and `getState` functions
 * as named arguments.
 *
 * @param {...Function} middlewares The middleware chain to be applied.
 * @returns {Function} A store enhancer applying the middleware.
 */
export default function applyMiddleware(...middlewares) {
  //可以这么做是因为在creatStore里,当发现enhancer是一个函数的时候
  // 会直接return enhancer(createStore)(reducer, preloadedState)
   
  return (createStore) => (...args) => {
    // 之后就在这里先建立一个store
    const store = createStore(...args)
    let dispatch = store.dispatch
    let chain = []
    // 将getState 跟dispatch函数暴露出去
    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)
    }
    //这边返回chain的一个数组,里面装的是wrapDispatchToAddLogging那一层,相当于先给
     middle剥了一层皮,也就是说
    // 接下来只需要开始传入dispatch就行
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    
    dispatch = compose(...chain)(store.dispatch)
    // wrapCrashReport(wrapDispatchToAddLogging(store.dispatch))
    // 此时返回了上一个dispatch的函数作为wrapCrashReport的next参数
    // wrapCrashReport(dispatchAndLog)
    // 最后返回最终的dipatch
    return {
      ...store,
      dispatch
    }
  }
}

总结,其实每一个middleware都在增强dispatch的功能,在dispatch action的前后搞点事情~

参考文档:
http://redux.js.org/docs/adva...
https://github.com/reactjs/re...
https://github.com/reactjs/re...
https://github.com/reactjs/re...


幽_月
316 声望72 粉丝

引用和评论

0 条评论