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
网友评论