Redux 洋葱模型理解
Posted Hello World
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 洋葱模型理解的主要内容,如果未能解决你的问题,请参考以下文章