内容参考技术胖老师文章
Redux进阶
一、中间件
这个中间件是redux
的中间件,不是react
的中间件。中间件可以用来做什么?比如,dispatch
在进行传递action
对象之后到达reducer
之前这段时间进行一些额外的操作就需要用到中间件middleware
,在实际工作中可以用来进行调用异步接口或路由,还可以用来进行日志记录、创建崩溃报告。(中间件是对dispatch
API作用的增强)
二、Redux中间件
1.Redux-thunk中间件
(1)Redux-thunk
配置
Redux-thunk
不是在Redux
基础组件中,因此需要进行安装
npm install --save redux-thunk
(2)配置Redux-thunk
组件:在Redux
中引入中间件applyMiddleware
官网用法:
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
reducers,
applyMiddleware(thunk)
);
但是使用官网这个用法就会无法使用React Devoloper Tools
这个Chrome浏览器插件。如果想两个都使用的话就需要使用增强函数:首先引入compose
import {createStore, applyMiddleware, compose} from 'redux'
然后利用compose
创建一个增强函数,代码如下:
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
将thunk
加进来,这样两个函数就都会执行了。
const enhancer = composeEnhancers(applyMiddleware(thunk))
绕一圈后将createStore
函数中的第二个变量替换为enhancer
,这样插件也可以使用了。
2.redux-thunk
源码分析:
位置:node_moudel/redux-thunk/src/index
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
源码中所暴露出来的thunk
是经过函数createThunkMiddleware
进行判断的。