react hook axios loading 合并多次弹出

多接口请求时,要加个loading,以前做的是接口请求一次,loading加载,然后结束loading关闭,但是会出现打开,关闭又打开的情况,

产品经理需要弹出一次,最后一次请求完成才关闭,然后这样就只能通过计数完成,request时 加 1,response 时减1,大于0 loading, 等于0 关闭,
项目中用的是useHook

import { useState, useCallback, useMemo, useEffect } from "react";
import Axios from "axios";
const _axios = Axios.create({
baseURL: host,
timeout: 30000,
});

export const useLoadingHandler = () => { const [num, setNum] = useState(0); const inc = useCallback(() => setNum((i) => i + 1), [ setCounter, ]); // add const dec = useCallback(() => setNum((i) => i - 1), [ setCounter, ]); // minus const interceptors = useMemo( () => ({ request: (config: any) => (inc(), config), response: (response: any) => (dec(), response), error: (error: any) => (dec(), Promise.reject(error)), }), [inc, dec] ); useEffect(() => { const req = _axios.interceptors.request.use( interceptors.request, interceptors.error ); const res = _axios.interceptors.response.use( interceptors.response, interceptors.error ); return () => { _axios.interceptors.request.eject(req); _axios.interceptors.response.eject(res); }; }, [interceptors]); return [num > 0]; };

 

posted @ 2021-04-28 11:36  小猪宿州  阅读(350)  评论(0编辑  收藏  举报