Redux中间件
redux中间件作用于action与store之间
其实就是对store的dispatch方法做一个升级
引入中间件之后,如果dispatch的参数是一个对象,它会直接将对象传递给store,如果参数是一个函数,那么dispatch会让这个函数先执行完毕,需要调用store的时候再用函数调用store
Redux-thunk vs Redux-Saga
redux-thunk的思路是将异步请求放在action中去实现,而redux-saga是将异步请求抽取出来单独放在一个文件里,相对来说redux-thunk原理更简单
Redux-Saga的使用
首先,安装redux-saga,在创建store的时候使用
store/index.js
import {createStore,applyMiddleware,compose} from 'redux';
import reducer from './reducer';
import createSagaMiddleWare from 'redux-saga';
import mySaga from './sagas';
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);
export default store;
在actionTypes.js中定义type
export const GET_LIST_SAGA='get_list_saga';
在actionCreator.js中创建action
export let getHandleAjaxAction=(value)=>({
type:HANDLE_AJAX_RES,
value
});
export let getListSaga=()=>({
type:GET_LIST_SAGA
});
在antdTodoList.js中派发一个action
componentDidMount(){
const action=getListSaga();
store.dispatch(action);
}
创建store/sagas.js(导出的必须是生成器函数)
配置了redux-saga之后,不仅reducer能接收到action,saga.js文件里的mySaga函数也能接收到,利用takeEvery判断type并且执行fetchList函数,因此我们在fetchList里面处理异步请求
import {takeEvery,put} from 'redux-saga/effects';
import {getHandleAjaxAction} from './actionCreator';
import {GET_LIST_SAGA} from './actionTypes';
import axios from 'axios';
function * fetchList(){
let res=yield axios.get('http://localhost:5000/data');
const action=getHandleAjaxAction(res.data);
yield put(action);
}
function * mySaga(){
yield takeEvery(GET_LIST_SAGA,fetchList);
}
export default mySaga;
效果如下: