手写applyMiddleware

middleware的本质,是一个调用后可以得到dispatch创建函数的函数

compose:函数组合,将一个数组中的函数进行组合,形成一个新的函数,该函数调用时,实际上是反向调用之前组合的函数

  1. export default function (...funcs) {
  2. if (funcs.length === 0) {
  3. return args => args;
  4. }
  5. if (funcs.length === 1) {
  6. return funcs[0];
  7. }
  8. return function (...args) {
  9. let lastReturn = null;
  10. for (let i = funcs.length - 1; i >= 0; i--) {
  11. const func = funcs[i];
  12. if (i === funcs.length - 1) {
  13. lastReturn = func(...args);
  14. } else {
  15. lastReturn = func(lastReturn);
  16. }
  17. }
  18. return lastReturn;
  19. }
  20. // return funcs.reduce((a, b) => (...args) => a(b(...args)));
  21. }
  1. import compose from './compose'
  2. export default function (...middlewares) {
  3. return function (createStore) { //给我创建仓库的函数
  4. //下面的函数用于创建仓库
  5. return function (reducer, defaultState) {
  6. //创建仓库
  7. const store = createStore(reducer, defaultState);
  8. let dispatch = () => { throw new Error("目前还不能使用dispatch") };
  9. const simpleStore = {
  10. getState: store.getState,
  11. dispatch: store.dispatch
  12. }
  13. //给dispatch赋值
  14. //根据中间件数组,得到一个dispatch创建函数的数组
  15. const dispatchProducers = middlewares.map(mid => mid(simpleStore));
  16. dispatch = compose(...dispatchProducers)(store.dispatch);
  17. return {
  18. ...store,
  19. dispatch
  20. }
  21. }
  22. }
  23. }