saga 中 thunk 调度的替代方案是什么?

Sha*_*ika 1 javascript reactjs react-native redux-thunk redux-saga

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

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);
};
Run Code Online (Sandbox Code Playgroud)

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

Abh*_*del 5

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

这是 redux-saga 官方文档的示例

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});
   }
}
Run Code Online (Sandbox Code Playgroud)

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

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);
};
Run Code Online (Sandbox Code Playgroud)

在你的工人传奇中:

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

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