在实际的工作中我们可以使用middleware(中间件)来进行日志记录、创建崩溃报告、调用异步接口或路由,比如在dispatch一个action到store之后,在到达reducer进行事务逻辑处理时,如果要进行一些额外操作,就需要用到middleware。中间件可以使用Redux-thunk来进行增强,是对dispatch的加强。
安装Redux-thunk
在终端输入以下命令:
npm install --save redux-thunk
配置Redux-thunk
在Redux中引入中间件,引入位置是store/index.js:
import {createStore,applyMiddleware} from 'redux';
引入redux-thunk库:
import thunk from 'redux-thunk';
按照官方文档,只需要将thunk放到createStore函数的第二个参数即可,但由于之前配置Redux Dev Tools,占去了第二个参数的位置。为了使两个插件都能使用,我们要用到增强函数。首先在store/index.js中引入compose:
import {createStore,applyMiddleware,compose} from 'redux';
创建一个增强函数:
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
将thunk加入:
const enhancer = composeEnhancers(applyMiddleware(thunk));
这个时候将enhancer放入createStore的第二个参数就可以了,两个函数都会执行:
const store = createStore(
reducer,
enhancer
);
store/index.js完整的代码如下:
import {createStore,applyMiddleware,compose} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const enhancer = composeEnhancers(applyMiddleware(thunk));
const store = createStore(
reducer,
enhancer
);
export default store;
//store必须是唯一的,只有reducer可以改变store