需求中,在特定交互行为时,中断已发起但未结束的 http 请求。比如:发生路由切换,关闭tab页,或者点击取消按钮等等。
import React from 'react';
import axios from 'axios';
const CancelToken = axios.CancelToken;
let cancel;
const AbortHTTP: React.FC = (props) => {
const handleAbort = () => {
cancel('中断请求');
};
const handleFetch = (e) => {
// 如果请求走的是二次封装后的axios,传参方式要自己调整下,重点就是能接收 cancelToken 参数就行
axios.post('url', // 接口地址
{
// 请求参数
},
{
cancelToken: new CancelToken(function executor(c) {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
}),
},
)
.then(() => {})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log(thrown.message);
} else {
// 处理错误
}
});
e.preventDefault();
e.cancelBubble = true;
};
return (
<>
<button onClick={handleFetch}>请求</button>
<button onClick={handleAbort}>停止</button>
</>
);
};
export default AbortHTTP;
路由切换提示
import { Prompt } from 'react-router-dom';
// when:控制提示展示状态,boolean,默认值true,当路由发生变化时,在当前页做出提示。
// message:提示文案。
<Prompt when={true} message={() => '提示信息'} />
关闭标签页,重新加载标签页的提示
useEffect(() => {
window.addEventListener('beforeunload', handleTabClosing);
window.addEventListener('unload', handleTabClosing);
return () => {
window.removeEventListener('beforeunload', handleTabClosing);
window.removeEventListener('unload', handleTabClosing);
};
},[]);
const handleTabClosing = (event) => {
event.preventDefault();
event.returnValue = '提示信息'; // 大部分浏览器只能展示浏览器默认的文本
};