首页 > 代码库 > Redux 洋葱模型理解
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>
Redux 洋葱模型理解
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。