在 useEffect 未运行时取消 Axios 请求 [英] Cancel Axios request in useEffect not running
问题描述
我正在尝试取消 axios 请求,但我只取得了部分成功.我有这个函数在我发出 GET 请求时返回一个 Promise:
I am attempting to cancel an axios request, but I am only having partial success. I have this function that returns a Promise when I make a GET request:
const getCards = (token) => {
const URL = isDev
? "https://cors-anywhere.herokuapp.com/https://privacy.com/api/v1/card"
: "https://privacy.com/api/v1/card";
const config = {
headers: {
Authorization: `Bearer ${token}`,
},
cancelToken: source.token,
};
return axios.get(URL, config);
};
我在 updateCards()
中调用这个函数,它看起来像这样:
I call this function inside updateCards()
which looks like this:
const updateCards = async () => {
console.log("Updating Cards");
setCards([]);
setStarted(true);
setLoading(true);
let response = await getCards(token).catch((thrown) => {
if (axios.isCancel(thrown)) {
console.error("[UpdateCards]", thrown.message);
}
});
/**
* response is undefined when we cancel the request on unmount
*/
if (typeof response === "undefined") return console.log("Undefined");
console.log("Got Response from UpdateCards", response);
setLoading(false);
};
我在 useEffect 钩子中取消了我的请求:
I cancel my request in the useEffect hook as so:
useEffect(() => {
return () => {
source.cancel()
}
}, [])
我已经在我的状态声明下设置了我的 CancelToken,如下所示:
And I have setup my CancelToken under my state declaration like this:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
我的问题是,如果我在 useEffect() 内部调用我的 updateCards() 函数,我可以很好地取消它,但是如果我使用按钮来调用相同的函数,则不会运行取消.我到处寻找,我发现的唯一解决方案是我必须在 useEffect() 挂钩中调用我的请求,但这不是我想做的事情.我该从哪里开始?
My issue is that, if I call my updateCards() function inside of the useEffect(), I can cancel it just fine, but if I use a button to call that same function the cancel is not ran. I have looked everywhere and the only solution I have found is that I have to call my requests within the useEffect() hook, but that is not something I want to do.Where do I go from here?
以下是我看过的资源:
https://github.com/axios/axios#cancellation
推荐答案
有一个地方来存储一个变量,其行为类似于 实例变量,可以使用useRef
.它是您想要的任何东西的容器.您可以将 CancelToken 存储在那里:
To have a place to store a variable that behaves like an instance variable of the component, you can use useRef
. It's a container for anything you want. You can store the CancelToken in there:
function Privacy(props) {
const source = useRef(null);
function getSource() {
if (source.current == null) {
const CancelToken = axios.CancelToken;
source.current = CancelToken.source();
}
return source.current;
}
useEffect(() => {
return () => {
if (source.current != null) source.current.cancel();
}
}, [])
// call `getSource()` wherever you need the Axios source
}
这篇关于在 useEffect 未运行时取消 Axios 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!