概述:
react-saga有3个重要的函数:call ,put takeEvery。
- call:在worker saga里执行异步函数;
- put:异步函数有结果的时候,派发action;
- takeEvery:当监听到aciton时,执行worker saga。
saga主要用到的是generator。
使用:
新建sagas.js
import { takeEvery , put} from 'redux-saga/effects'
import axios from 'axios';
import { GET_INIT_LIST } from './actionType';
import { initListAction} from './actionCreator';
//worker saga
function* todolist() {
//异步获取数据
try{
const res = yield axios.get('api/list');
const action=initListAction(res.data);
yield put(action);
}catch(e){
console.log('list.json 网络请求失败')
}
}
//当type为GET_INIT_LIST的action触发时,调用todolist函数
function* mySaga() {
yield takeEvery(GET_INIT_LIST, todolist);
} export default mySaga;
创建store的时候,按照文档配置好redux-saga
import { createStore, applyMiddleware ,compose} from 'redux';
import reducer from './reducer'
import createSagaMiddleware from 'redux-saga'
import mySaga from './sagas'
//1.创建中间件
const sagaMiddleware = createSagaMiddleware();
//2.应用中间件
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware));
const store = createStore(reducer, enhancer);
//3.执行run
sagaMiddleware.run(mySaga)
export default store;
组件里还是和之前一样
componentDidMount(){
const action=getInitListAction();
store.dispatch(action);
}