Redux之中间件的原理和applyMiddleware、Thunk的实现

现在我们的Redux和React-Redux已经基本实现了,在Redux中,触发一个action,reducer立即就能算出相应的state,如果我要过一会才让reducer计算state呢怎么办?也就是我们如何实现异步的action呢?这里就要用到中间件(middleware)

1. 中间件(middleware)介绍


中间就是在action与reducer之间又加了一层,没有中间件的Redux的过程是:action -> reducer,而有了中间件的过程就是action -> middleware -> reducer,使用中间件我们可以对action也就是对dispatch方法进行装饰,我们可以用它来实现异步action、打印日志、错误报告等功能。

又是装饰器,没错,这块的好多东西都离不开装饰器模式,所以,设计模式很重要。

关于中间件,有很多框架或者是类库都使用了中间件,像express、koa、mongoose等都有使用。

2. Redux中间件的使用


我们可以使用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了。

export function addAsync(){
  return dispatch => {
    setTimeout(() => {
      dispatch(add())
    }, 2000);
  }
}

想要实现中间件,我们首先有两个任务要做:

  1. 扩展createStore方法,使它可以接收第二个参数。

  2. applyMiddleware方法的实现。

猜你喜欢

转载自www.cnblogs.com/110162-wsx/p/10252950.html