美文网首页
redux-saga使用

redux-saga使用

作者: key君 | 来源:发表于2019-11-14 09:22 被阅读0次

    项目地址:
    https://github.com/iosKey/redux-saga

    概述:
    redux-saga是副作用(数据获取、浏览器缓存)易于管理、执行、测试和失败处理

    安装路由
    yarn add react-router-dom -S
    安装redux-saga
    npm install --save redux-saga
    yarn add redux-saga -S
    安装react-redux
    yarn add react-redux -S
    安装redux-thunk
    yarn add redux-thunk -S

    store.js saga为中间件的形式接入,配置createStore使用
    import { createStore, combineReducers, applyMiddleware } from "redux";
    import thunk from "redux-thunk";
    import createSagaMiddleware from "redux-saga";
    import mySaga from "./MySaga";
    
    const loginInfo = {
      isLogin: false,
      loading: false,
      err: "",
      user: {
        name: ""
      }
    };
    function loginReducer(state = { ...loginInfo }, action) {
      switch (action.type) {
        case "getUserInfo":
          return { ...loginInfo, loading: true };
        case "loginSuccess":
          return {
            ...state,
            loading: false,
            isLogin: true,
            user: { name: "xiaomi" }
          };
        case "loginFailed":
          return {
            ...state,
            loading: false,
            err: action.err,
            isLogin: false,
            user: { name: "" }
          };
        default:
          return { ...state };
      }
    }
    
    const sagaMw = createSagaMiddleware();
    
    const store = createStore(
      combineReducers({
        user: loginReducer
      }),
      // applyMiddleware(thunk)
      applyMiddleware(sagaMw)
    );
    sagaMw.run(mySaga);
    
    export default store;
    
    
    MySaga.js 当点击登录的时候 saga用takeEvery监听action,然后写对应的逻辑函数 put方法实际就是reducer dispatch更新状态,call方法做异步处理
    //call调用异步操作 put状态更新 takeEvery做saga监听
    import { call, put, takeEvery } from "redux-saga/effects";
    //说白了saga是用于异步的 用来代替thunk
    //模拟登录接口
    const UserService = {
        login(name){
            return new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    if(name === '小明'){
                        resolve({name: '小明'});
                    }else{
                        reject("用户名或密码错误")
                    }
                },1000);
            });
        }
    }
    
    function *loginHandle(action){
        try {
            //先loading起来
           yield put({type: 'getUserInfo'})
            //调用UserService的login方法 传参action.name 异步操作
           const res = yield call(UserService.login,action.name); 
           //更新状态 做dispatch操作
           yield put({type: 'loginSuccess'})
        } catch (err) {
           yield put({type: 'loginFailed',err})
        }
    }
    
    function* mySaga() {
        //拿到action里面的type值 把action传给loginHandle
        yield takeEvery("login", loginHandle);
      }
    
    export default mySaga;
    

    相关文章

      网友评论

          本文标题:redux-saga使用

          本文链接:https://www.haomeiwen.com/subject/lfnhictx.html