Redux 洋葱模型理解

下面的代码会输出:

A middleware1 开始
C middleware2 开始
E middleware3 开始
======= G =======
F middleware3 结束
D middleware2 结束
B middleware1 结束

 

首先 middleware1, middleware2, middleware3 都先串联对象 middlewareAPI,

var middlewareAPI = {
  getState: store.getState,
  dispatch: (action) => dispatch(action)
}
middlewares.map(middleware => middleware(middlewareAPI));

 

然后内部是这样执行的 A1( A2( A3(store.dispatch) ) )( actionCreate() ),

A3的next 是store.dispatch, A2的next 是A3最里层的函数, A1的next 是A2里最里层的函数。

var A1 = function(next) {
  return function(action) {
    console.log('A middleware1 开始');
    next(action)
    console.log('B middleware1 结束');
  };
};

var A2 = function(next) {
  return function(action) {
    console.log('C middleware2 开始');
    next(action)
    console.log('D middleware2 结束');
  };
};

var A3 = function(next) {
  return function(action) {
    console.log('E middleware3 开始');
    next(action)
    console.log('F middleware3 结束');
  };
};

 

 

<!DOCTYPE html>
<html>
<head>
  <script src="//cdn.bootcss.com/redux/3.5.2/redux.min.js"></script>
</head>
<body>
<script>
function middleware1(store) {
  return function(next) {
    return function(action) {
      console.log('A middleware1 开始');
      next(action)
      console.log('B middleware1 结束');
    };
  };
}

function middleware2(store) {
  return function(next) {
    return function(action) {
      console.log('C middleware2 开始');
      next(action)
      console.log('D middleware2 结束');
    };
  };
}

function middleware3(store) {
  return function(next) {
    return function(action) {
      console.log('E middleware3 开始');
      next(action)
      console.log('F middleware3 结束');
    };
  };
}
  
function reducer(state, action) {
  if (action.type === 'MIDDLEWARE_TEST') {
    console.log('======= G =======');  
  }
  return {};
}
  
var store = Redux.createStore(
  reducer,
  Redux.applyMiddleware(
    middleware1,
    middleware2,
    middleware3
  )
);

store.dispatch({ type: 'MIDDLEWARE_TEST' });
</script>
</body>
</html>

 

posted @ 2017-05-29 18:08  zhengming  阅读(632)  评论(0编辑  收藏  举报