目的: 通过compose组合函数方式 重写store.dispath方法

核心原理:看注释

  1. // createStore(reducer, preloadedState, enhancer)通过判断第二个或者第三个参数是否为方法来判断
  2. // 是否运用中间件
  3. // enhancer = applyMiddleware(func1,loggerMiddleware) 中间件的运用函数
  4. // 有中间件的情况return enhancer(createStore)(reducer, preloadedState)
  5. // 先生成旧的store再和dispath合并合成新的store
  6. const applyMiddleware = (...middlewares) => (createStore) => (reducer, preloadedState) =>{
  7. const store = createStore(...args)
  8. //给middleware 统一分配store
  9. const chain = middlewares.map(middleware => middleware(store))
  10. dispatch = compose(...chain)(store.dispatch)
  11. //返回一个通过解构 重写dispath 新的store
  12. return {
  13. ...store,
  14. dispatch
  15. }
  16. }
  17. // 此处 next 为 store.dispatch
  18. const loggerMiddleware = store => next => action => {
  19. console.log('this state', store.getState());
  20. console.log('action', action);
  21. next(action);
  22. console.log('next state', store.getState());
  23. };

redux-thunk

thunk就是简单的action作为函数,在action进行异步操作,发出新的action。

https://www.jianshu.com/p/ae7b5a2f78ae

业务场景例子 下单流程 中间件注册 校验逻辑

  1. const compose = (funcs) => (val) => funcs.reduce(async (pre, cru) => (await cru(pre)), val)
  2. const poinMainCheck = async (next) => {
  3. console.log('check start')
  4. await new Promise((res) => {
  5. setTimeout(() => {
  6. res()
  7. }, 5 * 1000)
  8. })
  9. next()
  10. console.log('check over')
  11. }
  12. const toOrder = () => {
  13. console.log('toOrder')
  14. return 111
  15. }
  16. const applyMiddleware = (funcs) => compose(funcs)(toOrder)
  17. applyMiddleware([poinMainCheck])