[英]Redux-thunk and axios - request cancellation
I've an app with redux-thunk
, redux-pack
and axios
on board.我有一个带有
redux-thunk
、 redux-pack
和axios
的应用程序。
My actions looks like this:我的动作是这样的:
export const getEntities = () => (dispatch, getState, { api }) => {
return dispatch({
type: ENTITIES_LOAD,
promise: api.getEntities(),
meta: {},
});
};
I call them in componentDidMount
.我在
componentDidMount
调用它们。
My question is - what is the best way to cancel those actions along with the request itself?我的问题是 - 取消这些操作以及请求本身的最佳方法是什么? I've read about
Cancel Token
that axios
uses, but how should I cancel the action first?我已经阅读了
axios
使用的Cancel Token
,但我应该如何先取消操作?
I found myself cancelling the requests using cancel tokens.我发现自己使用取消令牌取消了请求。 Kind of a way out of this issue, but I attached them to a global variable (like
window
), so every time the request is made, the new token is added to an object (with its own key), and every time a request is finished, this key is removed.一种解决这个问题的方法,但我将它们附加到一个全局变量(如
window
),因此每次发出请求时,新令牌都会添加到一个对象(使用其自己的密钥),并且每次请求完成后,删除此密钥。
So I have something like this available inside the client part of the app:所以我在应用程序的客户端部分有类似的东西可用:
window.cancellationTokens = { myOwnTokenKey: theActualToken }
If in need of cancelling a request (eg user leaving a route that fetches data on componentDidMount
), I just do:如果需要取消请求(例如,用户离开获取
componentDidMount
数据的路由),我只需要:
cancelRequest(nameOfTheKey);
Function called cancelRequest
takes one argument, that is the actual key of the request and looks like this:名为
cancelRequest
函数接受一个参数,即请求的实际键,如下所示:
const cancelRequest = (keyName) => {
if (typeof window === 'undefined') return;
const cancelMethod = window.cancellationTokens[keyName];
if (!cancelMethod) return;
cancelMethod();
}
Maybe you should consider adding redux-saga, make action canceling easy.也许您应该考虑添加 redux-saga,使操作取消变得容易。 See the docs https://redux-saga.js.org/
请参阅文档https://redux-saga.js.org/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.