本文作者:IMWeb 黄qiong 原文出处:IMWeb社区 未经同意,禁止转载
在分析源码applyMiddleware 之前,让我们先看看middleware是个啥
Redux里我们都知道dispatch一个action,就会到达reducer,而middleware就是允许我们在dispatch action之后,到达reducer之前,搞点事情。
比如:打印,报错,跟异步API通信等等
下面,让我们一步步来理解下middle是如何实现的:
假设我们有个需求,想打印出dispatch的action之后,nextState的值。
如图:
先用一种很简单的方式去实现
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这个函数进来,而是希望在用dispatch的时候,直接自带这个功能,于是想到了,直接复写store里的dispatch.
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,比如一个middle完成打印功能,一个完成报错功能
先把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 store.dispatch,就可以在后面实现一个链式调用。
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
到了这一步,就该想想怎么把多个middle合进store里啦~ ,我们希望一个函数可以帮我们完成这件事,这样就可以直接使用applyMiddleware(store, middleware)
下面是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) {
// 这里有个比较巧妙地地方,就是传入createStore跟...args,为什么要这么做呢
// 可以先看看我们在用applyMiddleware的时候是怎么用的
createStore(
rootReducers, //reducer
preloadedState,
applyMiddleware( //enhancer
thunkMiddleware,
createLogger
)
)
createStore的部分源码是这样的
export default function createStore(reducer, preloadedState, enhancer) {
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
enhancer = preloadedState
preloadedState = undefined
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.')
}
// 在这里可以看到,如果第三个参数是函数也是我们的applyMiddleware,那就会直接返回这个,对于我们的applyMiddleware来说,就是直接把creatStore的权利放在了自己身上啊~
return enhancer(createStore)(reducer, preloadedState)
}
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.')
}
...
}
// 于是这里就有了在creatStore的时候传入了增强器enhancer,那就会走到这里来,由增强器的内部自己创建一个store,然后增强store的某一部分功能,返回出去。对于middleware来说,增强的当然就是dispatch的功能啦~
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/advanced/Middleware.html
https://github.com/reactjs/redux/blob/master/src/compose.js
https://github.com/reactjs/redux/blob/master/src/applyMiddleware.js
https://github.com/reactjs/redux/blob/master/src/createStore.js