翻看Redux的源码,能够发现,它主要输出createStore, combineReducers, bindActionCreators, applyMiddleware, compose 五个接口,
首先,让咱们先看看middleware是个啥html
Redux里咱们都知道dispatch一个action,就会到达reducer,而middleware就是容许咱们在dispatch action以后,到达reducer以前,搞点事情。react
好比:打印,报错,跟异步API通讯等等git
下面,让咱们一步步来理解下middle是如何实现的:es6
假设咱们有个需求,想打印出dispatch的action以后,nextState的值。github
如图:express
先用一种很简单的方式去实现redux
let action = toggleTodo('2'); console.log('dispatch', action); store.dispatch(action); console.log('next state', store.getState())
包裹进函数里 function dispatchAndLoge (store, action) { let action = toggleTodo('2'); console.log('dispatch', action); store.dispatch(action); console.log('next state', store.getState()) }
可是咱们并不想每次要用的时候都须要import这个函数进来,因此咱们须要直接替代。数组
直接替代store的dispatch,在原先的dispatch先后加上咱们的代码,把原先的store.dispatch放进next里。app
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里作。
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里用的时候把这个参数传下去。
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;
接着,在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...