React+TypeScript中使用useEffect配合setInterval如何先发请求再启动定时轮询
实现方案
直接将请求逻辑封装为独立可复用函数,先手动触发首次请求,待请求完成后再启动定时器即可,同时修正原代码的依赖缺失问题避免闭包陷阱,修改后的代码如下:
useEffect(() => { let interval: NodeJS.Timeout | null = null; // 封装独立的请求方法 const fetchHistoricPrices = async () => { try { const response: AxiosResponse<IHistoricPricesResponse> = await backendAPIAxios.get(`/history${search}`) if (!response.data.success) { return alert(`Failed to get historic prices with error: ${response.data.message}`) } sethistoricPricesState(response.data.data!); } catch (e) { alert(`Failed to get historic prices with error: ${e as AxiosError}`) } finally { // 首次请求结束后再启动定时轮询 interval = setInterval(fetchHistoricPrices, 300000); } }; // 立即触发首次请求 fetchHistoricPrices(); // 组件卸载时清理定时器,避免内存泄漏 return () => { if (interval) clearInterval(interval); }; // 补充search到依赖数组,确保参数更新后轮询同步生效 }, [sethistoricPricesState, search]);
可选优化
如果需要避免网络波动导致前一次请求未完成、后一次请求已经发起的并发问题,可以将setInterval替换为递归setTimeout,确保两次请求的间隔从上次请求结束后开始计算,仅需修改finally块逻辑:
finally { interval = setTimeout(fetchHistoricPrices, 300000); }
清理时对应使用clearTimeout即可。
内容的提问来源于stack exchange,提问作者user16657995
相关产品推荐
相关产品推荐

