feat: 事件请求防抖优化
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
// src/views/Community/index.js
|
// src/views/Community/index.js
|
||||||
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
||||||
import { useSearchParams, useNavigate } from 'react-router-dom';
|
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||||
|
import { debounce } from 'lodash';
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
Container,
|
Container,
|
||||||
@@ -272,18 +273,37 @@ const Community = () => {
|
|||||||
return { key, label: filterLabelMap[key] ? filterLabelMap[key](value) : `${key}: ${value}` };
|
return { key, label: filterLabelMap[key] ? filterLabelMap[key](value) : `${key}: ${value}` };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 创建防抖的 loadEvents 函数(500ms 防抖延迟)
|
||||||
|
const debouncedLoadEvents = useRef(
|
||||||
|
debounce((page) => {
|
||||||
|
logger.debug('Community', '防抖后执行 loadEvents', { page });
|
||||||
|
loadEvents(page);
|
||||||
|
}, 500)
|
||||||
|
).current;
|
||||||
|
|
||||||
// 初始化加载
|
// 初始化加载
|
||||||
// 注意: 只监听 searchParams 变化,不监听 loadEvents 等函数
|
// 注意: 只监听 searchParams 变化,不监听 loadEvents 等函数
|
||||||
// 这是为了避免 StockDetailPanel 打开时触发不必要的重新加载
|
// 这是为了避免 StockDetailPanel 打开时触发不必要的重新加载
|
||||||
// 如果未来 loadEvents 添加了新的状态依赖,需要在此处同步更新
|
// 防抖优化:用户快速切换筛选条件时,只执行最后一次请求
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
logger.debug('Community', 'useEffect 触发,searchParams 变化', {
|
logger.debug('Community', 'useEffect 触发,searchParams 变化', {
|
||||||
params: searchParams.toString()
|
params: searchParams.toString()
|
||||||
});
|
});
|
||||||
const page = parseInt(searchParams.get('page') || '1', 10);
|
const page = parseInt(searchParams.get('page') || '1', 10);
|
||||||
loadEvents(page);
|
|
||||||
loadPopularKeywords();
|
// 使用防抖加载事件
|
||||||
loadHotEvents();
|
debouncedLoadEvents(page);
|
||||||
|
|
||||||
|
// 热门关键词和热点事件不需要防抖(初次加载)
|
||||||
|
if (searchParams.get('page') === null || searchParams.get('page') === '1') {
|
||||||
|
loadPopularKeywords();
|
||||||
|
loadHotEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 组件卸载时取消防抖
|
||||||
|
return () => {
|
||||||
|
debouncedLoadEvents.cancel();
|
||||||
|
};
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [searchParams]); // 只监听 URL 参数变化
|
}, [searchParams]); // 只监听 URL 参数变化
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user