request.ts 770 B

123456789101112131415161718192021222324252627282930313233
  1. import { useRef, useEffect } from "react";
  2. export function useRequestController() {
  3. const controller = useRef<AbortController | null>(null);
  4. const cq = () => {
  5. if (controller.current) {
  6. controller.current.abort();
  7. }
  8. controller.current = new AbortController();
  9. return controller.current.signal;
  10. }
  11. const cr = () => {
  12. if (controller.current) {
  13. controller.current = null;
  14. }
  15. }
  16. useEffect(() => {
  17. // 清理函数,组件卸载时取消请求
  18. return () => {
  19. if (controller.current) {
  20. controller.current.abort();
  21. controller.current = null;
  22. }
  23. };
  24. }, []);
  25. return {
  26. cq, cr
  27. }
  28. }