wrapping dispatch() to log actions
logger 中间件
函数addLoggingToDispatch
,接受一个store为参数,返回一个新的dispatch方法,将store.dispatch覆盖,并log出相对应的action和state信息。
the addLoggingToDispatch function takes the dispatch from the store and returns a new version of dispatch that logs every action and the state
1 | const addLoggingToDispatch = (store) => { |
wrapping dispatch() to recognize promise
promise中间件
redux 只能dispatch普通的对象,不能dispatch promise
函数addLoggingToDispatch
,接受一个store为参数,返回一个新的能处理promise的dispatch方法,。
a function addPromiseSupport() that takes the store and returns a version of dispatch that supports promises.
1 | // promise action example |
the middleware chain
函数wrapDispatchWithMiddlewares
,接受store和middlrwares[array]两个参数。
a function wrapDispatchWithMiddlewares() that takes the store as the first argument, and the array of middlewares as the second.
1 | const wrapDispatchWithMiddlewares = (store, middlewares) => { |
修改addLoggingToDispatch()
和addPromiseSupportToDispatch()
将next作为参数提取出来
1 | const logger = (store) => (next) => { |
再修改wrapDispatchWithMiddlewares()
中间件的调用为store.dispatch = middleware(store)(store.dispatch)
1 | const wrapDispatchWithMiddlewares = (store, middlewares) => { |
Dispatching Actions Asynchronously with thunks
thunk中间件支持dispatch thunks,和其他的中间件一样,它接受store、next、action作为参数。如果action是一个函数,则将dispatch传给action,直接调用store.dispatch(action)
,否则返回next(action)
。
Functions returned from other functions are often called thunks
1 | // thunk action |