saga 中 thunk dispatch 的替代方法是什么?
What is the alternative to thunk dispatch in 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);
};
这里使用了thunk。我将 saga 应用到项目中,我想用 saga 重写。由于没有 API 调用,我不想通过 saga 发送到 reducer。我想直接从这个动作转到减速器。那么如何在不调度的情况下重写?
Saga 用于处理副作用,您可以使用 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
}
}
我还没有测试过,不过应该可以。
在我的反应项目中,我有以下代码。
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 发送到 reducer。我想直接从这个动作转到减速器。那么如何在不调度的情况下重写?
Saga 用于处理副作用,您可以使用 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
}
}
我还没有测试过,不过应该可以。