UNPKG

ht_hooks

Version:
50 lines 1.67 kB
//!请求失败后延迟 retryInterval 毫秒自动重试,重试最多 retryCount 次 import { useRef } from 'react'; var useRetryPlugin = function (fetchInstance, _a) { var retryInterval = _a.retryInterval, retryCount = _a.retryCount; // 👉 retryInterval:两次重试之间的间隔时间(毫秒)。 // 👉 retryCount:最多重试的次数。 var timerRef = useRef(); var countRef = useRef(0); var triggerByRetry = useRef(false); if (!retryCount) { //如果 retryCount = 0,说明不需要重试,直接返回空插件 return {}; } return { onBefore: function () { if (!triggerByRetry.current) { countRef.current = 0; } triggerByRetry.current = false; if (timerRef.current) { clearTimeout(timerRef.current); } }, onSuccess: function () { countRef.current = 0; }, onError: function () { countRef.current += 1; if (retryCount === -1 || countRef.current <= retryCount) { //#若没达到重试次数上限 // Exponential backoff var timeout = retryInterval !== null && retryInterval !== void 0 ? retryInterval : Math.min(1000 * Math.pow(2, countRef.current), 30000); timerRef.current = setTimeout(function () { triggerByRetry.current = true; fetchInstance.refresh(); //!等待 retryInterval 毫秒后再次调用 refresh() 重试 }, timeout); } else { countRef.current = 0; } }, onCancel: function () { countRef.current = 0; if (timerRef.current) { clearTimeout(timerRef.current); } } }; }; export default useRetryPlugin;