setInterval的问题:如果请求超时超过轮询间隔,会导致请求堆积,所以用setTimeOut递归,确保上一次请求完成,再等待间隔发起下一次请求
import { useState, useEffect, useRef } from 'react';
import { message } from 'antd';
import { getMeteringList } from '@/services/MeterDataQuery';
const AdvancedPollingDemo = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const timerRef = useRef<NodeJS.Timeout | null>(null);
const POLLING_INTERVAL = 5000;
const polling = async () => {
if (loading) return;
setLoading(true);
try {
const res = await getMeteringList({ pageSize: 15, pageNum: 1 });
if (res.code === 200) {
setData(res.rows || []);
}
} catch (error) {
console.error('轮询失败:', error);
} finally {
setLoading(false);
timerRef.current = setTimeout(() => {
polling();
}, POLLING_INTERVAL);
}
};
const startPolling = () => {
if (!timerRef.current) {
polling();
}
};
const stopPolling = () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
};
useEffect(() => {
startPolling();
return () => {
stopPolling();
};
}, []);
return (
<div>
<div>递归轮询示例 - 当前数据:{data.length} 条</div>
</div>
);
};
export default AdvancedPollingDemo;