Redux中间件
使用Redux中间件进行日志记录、创建崩溃报告、调用异步接口或路由。
redux-thunk
通过增强函数,同时使用中间件和redux-dev-tool
import { createStore , applyMiddleware ,compose } from 'redux'; // 引入createStore方法
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; //暴露出去
将componentDidMount中请求数据的业务逻辑写入actionCreator中(以前的action是对象,现在的action是函数)。
const getAxiosData = (dispatch)=>{
axios.get('.....')
.then((res) =>{
const data = res.data;
const action = getListAction(data);
dispatch(action);
})
}
redux-saga
import mySaga from './saga/mySaga';
import createSagaMiddleware from 'redux-saga';
const sagaMiddleware = createSagaMiddleware();
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose;
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware));
const store = createStore( reducer, enhancer) ;
sagaMiddleware.run(mySaga);
以mySaga作为入口函数,写saga的中间件业务逻辑,在入口函数中捕获传递过来的action类型,根据action类型调用相应的方法。