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.
网友评论