zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    Python(93)_网络编程基础
    Web前端(13)_路径
    Web前端(12)_注释
    Web前端(11)_base标签
    Python(91)_python复习
    Web前端(10)_css文本样式
    Web前端(9)_div+span等标签
    虚拟化(6)_CPU虚拟化
    虚拟化(5)_打开tcp监听
    虚拟化(4)_离线克隆与在线克隆
  • 原文地址:https://www.cnblogs.com/zhengming2016/p/6918632.html
Copyright © 2011-2022 走看看