首页 > 代码库 > Redux 中间件的执行顺序理解
Redux 中间件的执行顺序理解
Redux.applyMiddleware(thunk, middleware1) 和 Redux.applyMiddleware(middleware1, thunk) 的区别:
<!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Redux</title> <script type="text/javascript" src=http://www.mamicode.com/‘js/redux.js‘></script>"text/javascript"> function reducer(state, action) { // 首次调用本函数时设置初始 state state = state || { counter: 0 }; switch (action.type) { case ‘INCREMENT‘: console.log(‘reducer‘); return { counter: state.counter + 1 }; case ‘DECREMENT‘: return { counter: state.counter - 1 }; default: return state; // 无论如何都返回一个 state } } var thunk = (middleApi) => (next) => (action) => { if(typeof action == ‘function‘){ console.log(1); return action(middleApi.dispatch, middleApi.getState); } console.log(2); return next(action); } function middleware1(store) { return function(next) { return function(action) { console.log(‘middleware1 开始‘); next(action); console.log(‘middleware1 结束‘); }; }; } var inc = () => { return {type: ‘INCREMENT‘} } var incAsy = () => (dispatch) => { console.log(‘等待2秒‘); setTimeout( ()=>{ dispatch( inc() ); }, 2000); } function incAsy2(){ return (dispatch, getState)=>{ console.log(‘等待1秒‘); setTimeout( ()=>{ dispatch( incAsy() ); console.log(‘incAsy2 ‘); } ,1000); } } /* Redux.applyMiddleware(thunk, middleware1) log 如下: 1 等待1秒 1 等待2秒 incAsy2 2 middleware1 开始 reducer middleware2 开始 */ /* Redux.applyMiddleware(middleware1, thunk) log 如下: middleware1 开始 1 等待1秒 middleware1 结束 //注意这里触发 dispatch, 又从 middleware1 里面进去了 middleware1 开始 1 等待2秒 middleware1 结束 incAsy2 middleware1 开始 2 reducer middleware1 结束 */ var store = Redux.applyMiddleware(thunk, middleware1)(Redux.createStore)(reducer); store.dispatch( incAsy2() ); </script> </body> </html>
Redux 中间件的执行顺序理解
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。