如何递归调用redux saga watcher

时间:2019-01-12 12:27:02

标签: react-redux redux-saga

我正在努力递归地调用redux-saga观察程序,该方法与setInterval函数的工作原理相同,在该方法中,应该每隔n秒调用一次观察程序功能,我们可以像clearInterval这样清除间隔。

我的要求-

每隔n秒递归调用redux-saga观察者。在这里,n存储在商店中,并且可以对其进行更新。因此,当n将在商店中更新时,我们需要停止旧的监视程序功能(如clearInterval),并以更新的n秒重新启动旧的递归监视程序。

2 个答案:

答案 0 :(得分:1)

import { delay } from "redux-saga";
import {
  all,
  take,
  select,
  cancel,
  put,
  takeEvery,
  fork,
} from "redux-saga/effects";

export function* loop() {

  // Get the store
  const state = yield select();
  let n = state.n;

  // Will keep looping with a delay of n milliseconds,
  // where n is accessed from the store.
  while (true) {
    yield delay(n);
    yield put({ type: "CALLED_AGAIN" });
  }
}

export function* startProcess() {

  // Start the loop
  let task = yield fork(loop);
  let action = yield take(["END_PROCESS", "INC_TIMER"]);

  switch (action.type) {
    case "END_PROCESS":

      // For stopping the loop
      yield cancel(task);
      break;
    case "INC_TIMER":

      // While changing the duration of the timer:
      // 1) End the previous loop
      yield cancel(task);

      // 2) Change the timer(stored as n here)
      yield put({ type: "INC_TIMER_COMPLETED" });

      // 3) Start the recursive calls again
      yield put({ type: "START_PROCESS" });
      break;
    default:
      break;
  }
}

export function* watchStartTasks() {
  // Initially "START_PROCESS" is dispatched to start the recursive calls.
  yield takeEvery("START_PROCESS", startProcess);
}

export default function* rootSaga() {
  yield all([watchStartTasks()]);
}

答案 1 :(得分:0)

答案将根据某些条件而变化-例如,是否要在更改N之后等待N ms,或者是否明确想取消该工作人员-但这可能会给你一个大概的想法:

 String cmdText = "INSERT INTO TEST1 (Name,Age) VALUES (@Name,@Age)";
 cmd1.Parameters.Add("@Name", SqlDbType.VarChar, 255).Value = textBox1.Text;
 cmd1.Parameters.Add("@Age", SqlDbType.VarChar, 255).Value = textBox2.Text;

如果function * rootSaga() { let prevTask yield takeEvery(CHANGE_N, function*() { if (prevTask) prevTask.cancel(); const n = yield select(getN); task = yield throttle(n, FOO, fooSaga); }); } 不够用,您可能想使用throttledelay将其替换为自定义观察者。