这里我们学的中间件都是Redux的中间件,不是React的中间件。
Redux-saga也是非常常用的中间件,和Redux-thunk不相上下,但比thunk要复杂一些,这里我们也来学习一下。
一、安装
npm install --save redux-saga
二、配置
进入store/index.js,删除之前配置的thunk,引入saga:
import createSagaMiddleware from 'redux-saga';
store/index.js:
import {createStore,applyMiddleware,compose} from 'redux';
import reducer from './reducer';
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
);
export default store;
//store必须是唯一的,只有reducer可以改变store
新建store/sagas.js文件,内容如下:
function* mySaga(){}
export default mySaga
在store/index.js中引入mySaga:
import {createStore,applyMiddleware,compose} from 'redux';
import reducer from './reducer';
import createSagaMiddleware from 'redux-saga';
import mySagas 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(mySagas);//运行saga
export default store;
//store必须是唯一的,只有reducer可以改变store
先注释掉TodoList.js中的生命周期函数componentDidMount(之前使用的是thunk中间件获取列表,不注释运行会报错)。
三、Redux-saga异步获取TodoList数据
修改TodoList.js的生命周期函数componentDidMount,并引入getMyListAction函数:
componentDidMount() {
/**
* 使用Redux-thunk中间件获取列表
const action = getTodoList();
store.dispatch(action);
*/
/**使用Redux-saga中间件获取列表 */
const action = getMyListAction();
store.dispatch(action);
}
import { changeInputAction, addItemAction, deleteItemAction, getMyListAction} from './store/actionCreaters';
在store/actionCreaters.js文件中创建getMyListAction函数,并引入常量GET_MY_LIST:
export const getMyListAction = ()=>({
type:GET_MY_LIST
})
import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM,GET_LIST,GET_MY_LIST} from './actionTypes';
在store/actionTypes.js文件中新建常量GET_MY_LIST:
export const GET_MY_LIST = 'getMyList'
业务逻辑在sagas.js文件中:
import {put, takeEvery} from 'redux-saga/effects';
import { GET_MY_LIST } from './actionTypes';
import {getListAction} from './actionCreaters';
import axios from 'axios';
//generator函数,做异步处理
function* mySaga(){
yield takeEvery(GET_MY_LIST,getList)//等待监听GET_MY_LIST
}
function* getList(){
const res = yield axios.get('/mock/5fa9f41e234c9b0d8babebae/ReactDemo01/xiaojiejie');
const action = getListAction(res.data.data);
yield put(action);
}
export default mySaga;
数据获取成功。