coze-middleschool/src/hooks/useAbortController.ts

41 lines
888 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { useEffect, useRef } from 'react';
export function useAbortController() {
const controllerRef = useRef<AbortController | null>(null);
// 获取AbortSignal实例
const getSignal = () => {
if (!controllerRef.current) {
controllerRef.current = new AbortController();
}
return controllerRef.current.signal;
};
// 中止所有请求
const abortAll = () => {
if (controllerRef.current) {
controllerRef.current.abort();
controllerRef.current = null;
}
};
// 创建新的Controller并中止之前的请求
const recreate = () => {
abortAll();
controllerRef.current = new AbortController();
return controllerRef.current.signal;
};
// 组件卸载时自动中止所有请求
useEffect(() => {
return () => {
abortAll();
};
}, []);
return {
getSignal,
abortAll,
recreate
};
}