根据文档,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中的所有请求?
发布评论