Appearance
日志中间件
本节目标:理解“日志中间件”的核心思路,并能把它用于实际开发或面试表达。 我们改写了
dispatch方法,实现了在更改状态时打印前后的状态;//一、日志功能letoldDispatch=
store.dispatch;
store.dispatch= function
(action){
console.log('prevstate',store.getState());oldDispatch(action);console.log('nextstate',store.getState());return
action;
}
exportdefault
store;从上我们可以看出,其原理是将原来的dispatch函数包装一层,进行切片编程; 中间件的功能:
- 打印日志
- 异步操作
但是上面这种方案并不好。所以我们可以采用中间的方式;
src\store\index.js
import{
createStore,applyMiddleware } from
'redux';
importrootReducer from
'./reducers';
letstore =
createStore(rootReducer);
//异步操作应用
store.dispatch= function
(action){
setTimeout(()=\> {
oldDispatch(action);},
1000);return
action;// 源码如此
}
exportdefault
store;//发送请求,异步请求数据应用
store.dispatch= function
(action){
fetch('/user.json').then(res=\>
res.json()).then(res=\> {
console.log(res);oldDispatch(action);});
}
exportdefault
store;完整实现:
Src/redux-logger.js
import{
createStore,applyMiddleware } from
'redux';
importrootReducer from
'./reducers';
letstore =
createStore(rootReducer);
//中间件,不管是什么功能,格式是固定
// store=\> next =\> action =\> { /* todo */ }
- 它本身是一个函数
- 它会返回一个函数
- 返回的函数会再返回一个函数
// getState=store.getState,
dispatch=store.dispatch
functionlogger({getState,dispatch }) {return function
(next){//调用下一个中间件:next等同于store的原始的dispatch方法 return function
(action){//这个就是改造后的dispatch
console.log('prevstate',getState());next(action);console.log('nextstate',getState()); `}`
}
}
exportdefault
store;
letstore =
applyMiddleware(logger)(createStore)(rootReducer);Src/redux/applyMiddleware.js
import{ compose } from
"redux";
functionapplyMiddleware(...middlewares){return function
(createStore){return function
(reducer){let store =
createStore(reducer); `let`
dispatch; `//middlewareAPI`是给中间用的,就向中间暴露的接口`API`,越少越好,越灵活越好
`//store`传给`middleware` `1.`中间件可以拿 到`store`任意属性 `2.`
`let` `middlewareAPI` `=` `{`
`getState:`
store.getState,dispatch:action =\>
dispatch(action) `}`
`let` `chain` `=`
middlewares.map(middleware=\>
middleware(middlewareAPI)); `dispatch` `=`
compose(...chain)(store.dispatch); `return` `{`
...store, `dispatch`
`};`
`}`
}
}
exportdefault
applyMiddleware;