applyMiddleware 沉思录

 

let newStore = applyMiddleware(mid1, mid2, mid3, ...)(createStore)(reducer, null);

 

给({ getState, dispatch }) => next => action签名的函数组分步赋值并进行串联的过程;

整体上是dispatch的method swizzling;

 

export default function applyMiddleware(...middlewares) {

  return (next)  =>

     (reducer, initialState) => {

        var store = next(reducer, initialState);

        var dispatch = store.dispatch;

        var chain = [];

 

//({ getState, dispatch })

        var middlewareAPI = {

          getState: store.getState,

          dispatch: (action) => dispatch(action)

        };

 

//({ getState, dispatch })

        chain = middlewares.map(middleware => middleware(middlewareAPI));

 

//next

        dispatch = compose(...chain, store.dispatch);

        return {

          ...store,

          dispatch

        };

   };

}

 

export default store => next => action => {

    console.log('dispatch:', action);

    next(action);

    console.log('finish:', action);

}

 

export default ({ getState, dispatch }) => next => action => {

    console.log('dispatch:', action);

    next(action);

    console.log('finish:', action);

}

 

function compose(...funs) {

       return arg => funcs.reduceRight( (compose, f) => f(composed), arg)

   }

 

https://www.cnblogs.com/fe-linjin/p/10494763.html

 

 

https://stackoverflow.com/questions/41139585/what-is-the-next-in-applymiddleware

 

...middlewares (arguments): 遵循 Redux middleware API 的函数。每个 middleware 接受 StoredispatchgetState 函数作为命名参数,并返回一个函数。该函数会被传入 被称为 next 的下一个 middleware 的 dispatch 方法,并返回一个接收 action 的新函数,这个函数可以直接调用 next(action),或者在其他需要的时刻调用,甚至根本不去调用它。调用链中最后一个 middleware 会接受真实的 store 的 dispatch 方法作为 next 参数,并借此结束调用链。所以,middleware 的函数签名是 ({ getState, dispatch }) => next => action。

 

https://www.redux.org.cn/docs/api/applyMiddleware.html

posted @ 2019-07-12 12:37  zzfx  阅读(190)  评论(0编辑  收藏  举报