我正在尝试取消axios请求,但是我只获得了部分成功。我有此函数,当我发出GET请求时会返回一个Promise:
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()
内部调用此函数,如下所示:
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挂钩中的请求:
useEffect(() => {
return () => {
source.cancel()
}
}, [])
我已经按照下面的状态声明设置了CancelToken:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
我的问题是,如果我在useEffect()内部调用updateCards()函数,则可以取消它,但是如果我使用按钮调用该函数,则取消将不会运行。我到处都看过了,发现的唯一解决方案是我必须在useEffect()挂钩中调用我的请求,但这不是我想要做的事情。我从这里去哪里?
以下是我看过的资源:
答案 0 :(得分:2)
要在某个位置存储行为类似于组件instance variable的变量,可以使用useRef
。它是您想要的任何内容的容器。您可以在其中存储CancelToken:
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
}