8-中间件

作者: 钢笔先生 | 来源:发表于2020-01-29 16:17 被阅读0次

Time: 20200129

Is a suggested way to extend Redux with custom functionality.

redux-logger中间件为例

截屏2020-01-29下午4.06.50.png

先安装:yarn add redux-logger

然后代码中:

const redux = require('redux')  // nodejs version import
const reduxLogger = require('redux-logger')

// this is a function
const createStore = redux.createStore // not redux.createStore()
const combineReducers = redux.combineReducers
const applyMiddleware = redux.applyMiddleware
// 中间件
const logger = reduxLogger.createLogger()

// 应用中间件
const store = createStore(rootReducer, applyMiddleware(logger))

现在我们有logger来处理日志,我们就可以先删除自己写的监听处理函数,console.log(...)

const unsubscribe = store.subscribe(() => {})

输出日志如下:

initial state:  { cake: { numOfCakes: 10 }, iceCream: { numOfIceCreams: 20 } }
 action BUY_CAKE @ 16:13:41.315
   prev state { cake: { numOfCakes: 10 }, iceCream: { numOfIceCreams: 20 } }
   action     { type: 'BUY_CAKE', info: 'first redux action' }
   next state { cake: { numOfCakes: 9 }, iceCream: { numOfIceCreams: 20 } }
 action BUY_CAKE @ 16:13:41.320
   prev state { cake: { numOfCakes: 9 }, iceCream: { numOfIceCreams: 20 } }
   action     { type: 'BUY_CAKE', info: 'first redux action' }
   next state { cake: { numOfCakes: 8 }, iceCream: { numOfIceCreams: 20 } }
 action BUY_CAKE @ 16:13:41.320
   prev state { cake: { numOfCakes: 8 }, iceCream: { numOfIceCreams: 20 } }
   action     { type: 'BUY_CAKE', info: 'first redux action' }
   next state { cake: { numOfCakes: 7 }, iceCream: { numOfIceCreams: 20 } }
 action BUY_ICECREAM @ 16:13:41.321
   prev state { cake: { numOfCakes: 7 }, iceCream: { numOfIceCreams: 20 } }
   action     { type: 'BUY_ICECREAM', info: 'second redux action' }
   next state { cake: { numOfCakes: 7 }, iceCream: { numOfIceCreams: 19 } }
 action BUY_ICECREAM @ 16:13:41.323
   prev state { cake: { numOfCakes: 7 }, iceCream: { numOfIceCreams: 19 } }
   action     { type: 'BUY_ICECREAM', info: 'second redux action' }
   next state { cake: { numOfCakes: 7 }, iceCream: { numOfIceCreams: 18 } }

非常便于debug!

中间件是Redux中的一个非常重要的概念。

在下一节,我们将用到异步Action,这就需要用到中间件来完成。

END.

相关文章

网友评论

    本文标题:8-中间件

    本文链接:https://www.haomeiwen.com/subject/wlzvthtx.html