概述:
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);
}
