美文网首页
umi: 自定义hook,在react组件销毁时,取消所有ped

umi: 自定义hook,在react组件销毁时,取消所有ped

作者: 夏知寒 | 来源:发表于2023-01-02 17:46 被阅读0次

    useCancelable.ts

    import { useEffect, useCallback } from 'react';
    
    let apis: AbortController[] = [];
    const useCancelable = () => {
      const signFn = useCallback(
        <P, R>(fn: (args: P) => R) =>
          (args: P) => {
            const controller = new AbortController();
            const { signal } = controller;
            apis.push(controller);
            return fn.apply(null, [{ ...args, signal }]) as R;
          },
        [],
      );
    
      useEffect(() => {
        return () => {
          apis.forEach((controller) => {
            controller.abort();
          });
          apis = [];
        };
      }, []);
    
      return { signFn };
    };
    
    export default useCancelable;
    
    

    proRequest.ts

    import { request } from 'umi';
    import type {
      RequestOptionsWithResponse,
      RequestResponse,
      RequestOptionsWithoutResponse,
      RequestOptionsInit,
    } from 'umi-request';
    
    interface RequestMethodInUmi<R = false> {
      <T = any>(
        url: string,
        options: RequestOptionsWithResponse & { skipErrorHandler?: boolean },
      ): Promise<RequestResponse<T>>;
      <T = any>(
        url: string,
        options: RequestOptionsWithoutResponse & { skipErrorHandler?: boolean },
      ): Promise<T>;
      <T = any>(
        url: string,
        options?: RequestOptionsInit & { skipErrorHandler?: boolean },
      ): R extends true ? Promise<RequestResponse<T>> : Promise<T>;
    }
    const proRequest: RequestMethodInUmi = (url: string, options: any) => {
      const signal = (options?.data || options?.params).signal;
      delete (options?.data || options?.params).signal;
      return request<RequestMethodInUmi>(url, {
        ...options,
        signal,
      });
    };
    
    export default proRequest;
    

    使用方法:
    函数组件内

    const {signFn} = useCancelable();
    
    signFn(apiFn);
    

    services里使用proRequest替代umi-request

    相关文章

      网友评论

          本文标题:umi: 自定义hook,在react组件销毁时,取消所有ped

          本文链接:https://www.haomeiwen.com/subject/euqkcdtx.html