如何取消ComponentWillUnmount中的所有请求?

编程入门 行业动态 更新时间:2024-10-27 08:33:12
本文介绍了如何取消ComponentWillUnmount中的所有请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

根据文档,ComponentWillUnmount能够取消请求。

According to the docs, ComponentWillUnmount is able to cancel requests.

我有一个页面可以加载iframe的加载请求,以及其他页面请求。如果用户在页面处理请求时决定离开页面,我该如何取消这些请求,以免影响用户之后访问的其他页面?

I have a page that makes requests for an iframe to load, as well as other requests for page. If the user decides to navigate away from the page while the page is still processing the requests, how can I cancel those requests so that it doesn't affect the other pages the user goes to thereafter?

我应该注意到我正在使用Redux和Redux-saga。

I should note that I am using Redux and Redux-saga.

推荐答案

从技术上讲,你无法取消或中止承诺,因为Web浏览器不公开任何方法。

Technically you cannot cancel or abort a promise because the web browser does not expose any method for doing that.

如果用户导航到另一个页面,您可以做的只是忽略承诺。有两种方法可以做到这一点:

What you can do instead is to just ignore the promise if the user navigated to another page. There are two methods to do that:

你不应该这样做将您的应用程序状态存储在组件状态中。通过使用Redux,应用程序状态将在所有组件之间共享。然后将 redux-promise-middleware 与 Thunk 中间件,用于处理Redux中的异步操作。

You should not store your application state in your component state. By using Redux the application state will be shared amongst all components. Then you use redux-promise-middleware in combination with Thunk middleware to handle async actions in Redux.

简单地说,在你的行动可以做这样的事情:

Simply, in your action you can do something like this:

case 'LOAD_ORDERS_SUCCESS': if state.location != 'orders' { return } // store the data in the application state

使用RxJS和observables

Observables是Promises的另一种方式。

Using RxJS and observables

Observables is an alternative way to Promises.

有一个名为 redux-observable 和视频解释了Observable如何可以完全用于此原因。在他们的文档中查看配方:

There is a library called redux-observable and a video from Netflix that explain how Observable can be used exactly for this very reason. Check out this recipe in their docs:

const fetchUserEpic = action$ => action$.ofType(FETCH_USER) .mergeMap(action => ajax.getJSON(`/api/users/${action.payload}`) .map(fetchUserFulfilled) .takeUntil(action$.ofType(FETCH_USER_CANCELLED)) );

更多推荐

如何取消ComponentWillUnmount中的所有请求?

本文发布于:2023-11-26 14:19:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634112.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ComponentWillUnmount

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!