我有一个正常运作的redux传奇,但我无法停止思考它看起来多么丑陋。我正在努力做的事实是有点人为地模拟异步而不需要它,但我想延迟一秒然后再调用另一个函数 - similar to the tutorial。与教程(这是一个简单的增量器)的不同之处在于我实际上需要传递信息。我正是这样做的:
import { delay } from 'redux-saga';
import { put, call, takeEvery, all } from 'redux-saga/effects';
// Our worker Saga: will perform the add employee task
export function* addEmployeeAsync(action) {
yield call(delay, 1000);
console.log(action); // logs undefined on initial app load
const payload = action && action.payload;
yield put({ type: 'ADD_EMPLOYEE', payload });
}
// Our watcher Saga: spawn a new addEmployeeAsync task on each ADD_EMPLOYEE_ASYNC
export function* watchAddEmployeeAsync() {
yield takeEvery('ADD_EMPLOYEE_ASYNC', addEmployeeAsync);
}
export default function* rootSaga() {
yield all([
addEmployeeAsync(),
watchAddEmployeeAsync(),
]);
}
此功能也在页面加载时调用,有效负载为undefined
,这可能表示我缺少一个更大的问题。
重申一下,这段代码 正在运作,但我不禁想到必须有更清洁的方法来实现这一点。
答案 0 :(得分:2)
我想我找到了它。我不认为我需要在文件底部的all
中导出工作者传奇。我想只是导出观察者传奇来处理它(并防止有效负载未定义的初始调用)。
以下是我最终的结果:
import { delay } from 'redux-saga';
import { put, call, takeEvery, all } from 'redux-saga/effects';
// Our worker Saga: will perform the add employee task
export function* addEmployeeAsync({ payload }) {
yield call(delay, 1000);
yield put({ type: 'ADD_EMPLOYEE', payload });
}
// Our watcher Saga: spawn a new addEmployeeAsync task on each ADD_EMPLOYEE_ASYNC
export function* watchAddEmployeeAsync() {
yield takeEvery('ADD_EMPLOYEE_ASYNC', addEmployeeAsync);
}
export default function* rootSaga() {
yield all([
watchAddEmployeeAsync(),
]);
}
这对我来说似乎更清洁(因为我不必检查它是否未定义)。