zoukankan      html  css  js  c++  java
  • 使用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);
    }
    

      

  • 相关阅读:
    树链剖分(转载)
    随机数生成器
    错排公式的理解与推导(转载)
    容斥原理(转载)
    Luogu 3758 [TJOI2017]可乐(有向图邻接矩阵幂的意义 矩阵快速幂)
    vue input复选框checkbox默认样式纯css修改
    vue 页面切换的时候vuex记录之前的滚动条位置
    vue从入门到进阶
    es6 学习笔记
    vue 项目笔记
  • 原文地址:https://www.cnblogs.com/superlizhao/p/9441735.html
Copyright © 2011-2022 走看看