【问题标题】:Redux saga: how to cancel one task from another that didn't initiate it?Redux saga:如何从另一个没有启动它的任务中取消一个任务?
【发布时间】:2020-08-21 05:47:39
【问题描述】:

我正在阅读 this article 关于取消 Redux saga 中的任务的内容。基本上他们的例子是这样的:

function* main() {
  yield call(task1);
  yield cancel(task1);
}

function* task1() {
  <...>
}

这里main 可以取消task1,因为它调用了它。在我的代码中,我正在运行这样的函数:

function* task1() {
  <...>
}

function* task2() {
  yield cancel(task1);
}

function* main() {
  takeLatest(actionCreator1, task1);
  takeLatest(actionCreator2, task2);
}

task2 中取消task1 不起作用,大概是因为task2 没有调用task1。有谁知道我该如何解决这个问题?

【问题讨论】:

    标签: reactjs react-native asynchronous redux redux-saga


    【解决方案1】:

    解决方案可能是让 main 自己实现类似于 takeLatest 的东西,但有额外的逻辑来取消其他任务。

    如果你只想让 action2 做额外的取消,那么它看起来像这样:

    function* main() {
      let firstTask;
      let secondTask;
      while (true) {
        const action = yield take([actionCreator1, actionCreator2]);
        if (firstTask) {
          // Always cancel task 1, whether we got action 1 or action 2
          yield cancel(firstTask);
        }
        if (action.type === "the type of action 1") {
          firstTask = yield fork(task1, action);
        } else {
          if (secondTask) {
            // Only cancel task 2 if we got action 2
            yield cancel(secondTask);
          }
          secondTask = yield fork(task2, action);
        }
      }
    }
    

    如果你想让两个动作都取消两个任务,那就简单一点:

    function* main() {
      let task;
      while (true) {
        const action = yield take([actionCreator1, actionCreator2]);
        if (task) {
          yield cancel(task);
        }
        if (action.type === "the type of action 1") {
          task = yield fork(task1, action);
        } else {
          task = yield fork(task2, action);
        }
      }
    }
    

    【讨论】:

    • 我找到了一种更简单(但不太优雅)的方法来使用局部变量,但是在这里查看您的代码,您的逻辑是合理的,这是一个非常好的解决方案。我很感激!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2017-09-12
    相关资源
    最近更新 更多