基于动作类型及其数据的 ReduxObservable 取消 [英] ReduxObservable cancellation based on action type and its data

查看:56
本文介绍了基于动作类型及其数据的 ReduxObservable 取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 React 应用程序,它使用 redux-observable 和 typescript.在这种情况下, FetchAttribute Action 被一个 id 触发,然后进行 ajax 调用.在某些情况下,如果FETCH_ATTRIBUTE_CANCEL"操作使用与FetchAttributeAction"操作相同的 id 触发,我想取消 ajax 请求.

I have React app which uses redux-observable with typescript. In this scenario, FetchAttribute Action gets triggered with a id and then make an ajax call. In certain case, I would want to cancel the ajax request if "FETCH_ATTRIBUTE_CANCEL" action was triggered with the same id as of "FetchAttributeAction" action.

action$.ofType(FETCH_ATTRIBUTE)
    .switchMap((request: FetchAttributeAction) => {

      return ajax.getJSON(`/api/fetch-attribute?id=${request.id}`)
        .flatMap((fetchUrl) => {
            // return new action
        })
        .takeUntil(action$.ofType(FETCH_ATTRIBUTE_CANCEL));
    });

interface FetchAttributeAction{
  id: number;
}

问题:我们如何根据动作类型+动作数据取消执行?就我而言,它会是 FETCH_ATTRIBUTE_CANCEL 和 id.

Problem: How do we cancel the execution based on action type + action data? In my case, it would FETCH_ATTRIBUTE_CANCEL and id.

推荐答案

关键是将 takeUntil 通知器中的操作过滤为仅与您关心的 ID 匹配的操作.

The key is to filter actions in the takeUntil notifier to only those which match the ID you care about.

action$.ofType(FETCH_ATTRIBUTE_CANCEL).filter(action => action.id === request.id)

这里是它的样子:

演示:https://stackblitz.com/edit/redux-observable-playground-xztkoo?file=fetchAttribute.js

const fetchAttributeEpic = action$ =>
  action$.ofType(FETCH_ATTRIBUTE)
    .mergeMap(request =>
      ajax.getJSON(`/api/fetch-attribute?id=${request.id}`)
        .map(response => fetchAttributeFulfilled(response))
        .takeUntil(
          action$.ofType(FETCH_ATTRIBUTE_CANCEL).filter(action => action.id === request.id)
        )
    );

你也可以看看以前的问题:

You can also take a look at previous questions:

OP 还指出他们正在使用 switchMap(就像我最初复制他们的代码时一样),这意味着自 以来史诗一次只有一个 getJSONswitchMap 将取消订阅之前的内部 Observable.所以这也需要链接起来.好收获!

The OP also pointed out that they were using switchMap (as did I originally when I copied their code) which would have meant that the epic only ever had one getJSON at a time since switchMap will unsubscribe from previous inner Observables. So that also needed to be chained. Good catch!

这篇关于基于动作类型及其数据的 ReduxObservable 取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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