首页 > 解决方案 > 如果使用 takeLatest,如何取消 Saga 中的任务?

问题描述

我在应用程序中有许多表单并重用相同的表单,但使用不同的“id”我创建了一个组件,这个传奇:

export default function FormSaga(SEND_REQUEST) {
  return function* () {
    yield takeLatest(SEND_REQUEST, submit);
  };
}

但是如果我需要中止表单提交,Saga 的手册为我提供了这个解决方案:

function* main() {
  while ( yield take('START_BACKGROUND_SYNC') ) {
    // starts the task in the background
    const bgSyncTask = yield fork(bgSync)

    // wait for the user stop action
    yield take('STOP_BACKGROUND_SYNC')
    // user clicked stop. cancel the background task
    // this will cause the forked bgSync task to jump into its finally block
    yield cancel(bgSyncTask)
  }
}

我试过这个:

export default function FormSaga(SEND_REQUEST, ABORT_REQUEST) {
  return function* () {
    while (yield take(SEND_REQUEST)) {
      const submitTask = yield fork(submit);

      yield take(ABORT_REQUEST);
      yield cancel(submitTask);
    }
  };
}

但它不起作用。

如果有人可以帮助我重写我的 takeLatest 以便取消任务会起作用吗?谢谢!

标签: redux-saga

解决方案


猜猜找到了解决方案,看起来它正在工作。

    const task = yield takeLatest(SEND_REQUEST, submit);

    yield take(ABORT_REQUEST);
    yield cancel(task);

推荐阅读