【问题标题】:What is the alternative to thunk dispatch in saga?saga 中 thunk dispatch 的替代方法是什么?
【发布时间】:2020-04-29 22:37:00
【问题描述】:

在我的 react 项目中,我有以下代码。

import uuid from 'uuid';
import { SET_ALERT, REMOVE_ALERT } from './types';

export const setAlert = (msg, alertType, timeout = 5000) => dispatch => {
  const id = uuid.v4();
  dispatch({
    type: SET_ALERT,
    payload: { msg, alertType, id }
  });

  setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout);
};

这里已经使用了thunk。我将 saga 应用到项目中,我想用 saga 重写。由于没有 API 调用,我不想通过 saga 发送到减速器。我想直接从这个动作去减速器。那么如何在没有 dispatch 的情况下重写呢?

【问题讨论】:

    标签: javascript reactjs react-native redux-saga redux-thunk


    【解决方案1】:

    Sagas 用于处理副作用,您可以使用 put 直接从您的 saga 中调度操作。

    这里是redux-saga官方docs的例子

    import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
    import Api from '...'
    
    // worker Saga: will be fired on USER_FETCH_REQUESTED actions
    function* fetchUser(action) {
       try {
          const user = yield call(Api.fetchUser, action.payload.userId);
          yield put({type: "USER_FETCH_SUCCEEDED", user: user});
       } catch (e) {
          yield put({type: "USER_FETCH_FAILED", message: e.message});
       }
    }
    

    所以如果我要编写你的代码,它将是这样的:

    import uuid from 'uuid';
    import { SET_ALERT, REMOVE_ALERT } from './types';
    import { put } from 'redux-saga/effects'
    
    export const setAlert = (msg, alertType, timeout = 5000) => {
      const id = uuid.v4();
      put({
        type: SET_ALERT,
        payload: { msg, alertType, id }
      });
    
      setTimeout(() => put({ type: REMOVE_ALERT, payload: id }), timeout);
    };
    

    在你的工人传奇中:

    function* someAction(action) {
      try {
         // some logic
         yield setAlert(msg, 5000);
      } catch (e) {
         // some error handling logic
      }
    }
    

    我还没有测试过,但是它应该可以工作。

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 2019-06-15
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2023-04-10
      • 2015-01-04
      • 1970-01-01
      相关资源
      最近更新 更多