使用redux-saga中間件實現異步數據請求


概述:

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);
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM