如今咱们的Redux和React-Redux已经基本实现了,在Redux中,触发一个action,reducer当即就能算出相应的state,若是我要过一会才让reducer计算state呢怎么办?也就是咱们如何实现异步的action呢?这里就要用到中间件(middleware)express
中间就是在action与reducer之间又加了一层,没有中间件的Redux的过程是:action -> reducer
,而有了中间件的过程就是action -> middleware -> reducer
,使用中间件咱们能够对action也就是对dispatch方法进行装饰,咱们能够用它来实现异步action、打印日志、错误报告等功能。redux
又是装饰器,没错,这块的好多东西都离不开装饰器模式,因此,设计模式很重要。设计模式
关于中间件,有不少框架或者是类库都使用了中间件,像express、koa、mongoose等都有使用。app
咱们能够使用Redux提供的applyMiddleware方法来使用一个或者是多个中间件,将它做为createStore的第二个参数传入便可,咱们以Redux-Thunk为例框架
import { createStore, applyMiddleware } from ‘redux‘ import thunk from ‘redux-thunk‘ const store = createStore(counter, applyMiddleware(thunk)) ReactDOM.render( ( <Provider store={store}> <App /> </Provider> ), document.getElementById(‘root‘) )
经过thunk中间件,咱们就能够实现异步的action了。koa
export function addAsync(){ return dispatch => { setTimeout(() => { dispatch(add()) }, 2000); } }
想要实现中间件,咱们首先有两个任务要作:异步
扩展createStore方法,使它能够接收第二个参数。mongoose
applyMiddleware方法的实现。ide