如何让 takeLatest 考虑 url、params 和 method? [英] How do I make takeLatest consider url, params, and method?

查看:43
本文介绍了如何让 takeLatest 考虑 url、params 和 method?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Saga 的 takeLatest 来中止除最新请求之外的所有请求.这工作正常,但现在我只想中止具有相同网址、参数和方法的请求.

I'm using Saga's takeLatest to abort all requests except the latest. This works fine, but now I want to only abort requests which don't have identical url, params, and method.

我知道 Saga 使用 type 属性来比较动作(就像 vanilla Redux 那样),但我还添加了 urlparamsmethod 到我的操作中,因为我希望有某种方法可以做类似

I know Saga uses the type attribute to compare actions (just like vanilla Redux does), but I've also added url, params, and method to my actions because I was hoping there there was some way to do something like

yield takeLatestIf((action, latestAction) => {
    const sameType = action.type === latestAction.type;
    const sameUrl = action.url === latestAction.type;
    const sameParams = areEqual(action.params, lastAction.params);
    const sameMethod = action.method === lastAction.method;

    return sameType && sameUrl && sameParams && sameMethod;
});

只有在所有 4 个属性比较都为 false 时才应中止请求.

which should only abort requests if all 4 of those attribute comparisons are false.

我怎样才能做到这一点?

How can I accomplish this?

推荐答案

如果我从你的问题中猜对了,你想要这个:

If I get it right from your question, you want this:

  1. 就像标准的takeLatest().
  2. 但是当发出重复的请求时,忽略它并等待已经执行的请求(一个合理的用例).

所以我采用了 takeLatest() 实现 在文档中提供 并根据您的情况进行调整:

So I took takeLatest() implementation provided in the docs and adapted it to your scenario:

const takeLatestDeduped = (patternOrChannel, compareActions, saga, ...args) => fork(function*() {
  let lastTask
  let lastAction
  while (true) {
    const action = yield take(patternOrChannel)
    // New logic: ignore duplicate request
    if (lastTask && lastTask.isRunning() && !compareActions(lastAction, action)) {
      continue
    }
    if (lastTask) {
      yield cancel(lastTask)
    }
    lastTask = yield fork(saga, ...args.concat(action))
    // New logic: save last action
    lastAction = action
  }
})

我们有三种情况:

  1. 没有正在运行的任务:开始新的任务 - 标准行为
  2. 正在运行的任务,没有重复:取消旧任务,开始新任务 - 标准行为
  3. 正在运行的任务,得到重复:忽略 - 新的自定义行为

所以我添加了 case #3 逻辑:

So I added case #3 logic:

  1. 忽略重复的请求(在这种情况下不应该做任何事情,所以我继续处理下一个动作).
  2. 保存上次操作以备将来重复检查.

这篇关于如何让 takeLatest 考虑 url、params 和 method?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆