feat: 优化依赖

This commit is contained in:
zdl
2025-10-24 17:18:08 +08:00
parent 5aebd4b113
commit 6f34cab6d1

View File

@@ -67,7 +67,11 @@ export default function CenterDashboard() {
const location = useLocation();
const navigate = useNavigate();
const toast = useToast();
// ⚡ 提取 userId 为独立变量,避免 user 对象引用变化导致无限循环
const userId = user?.id;
const prevUserIdRef = React.useRef(userId);
// 颜色主题
const textColor = useColorModeValue('gray.700', 'white');
const borderColor = useColorModeValue('gray.200', 'gray.600');
@@ -107,13 +111,13 @@ export default function CenterDashboard() {
if (jc.success) setEventComments(Array.isArray(jc.data) ? jc.data : []);
} catch (err) {
logger.error('Center', 'loadData', err, {
userId: user?.id,
userId,
timestamp: new Date().toISOString()
});
} finally {
setLoading(false);
}
}, [user?.id]); // 只依赖 user.id,避免无限循环
}, [userId]); // ⚡ 使用 userId 而不是 user?.id
// 加载实时行情
const loadRealtimeQuotes = useCallback(async () => {
@@ -188,7 +192,14 @@ export default function CenterDashboard() {
};
useEffect(() => {
if (user && location.pathname.includes('/home/center')) {
const userIdChanged = prevUserIdRef.current !== userId;
if (userIdChanged) {
prevUserIdRef.current = userId;
}
// 只在 userId 真正变化或路径变化时加载数据
if ((userIdChanged || !prevUserIdRef.current) && user && location.pathname.includes('/home/center')) {
loadData();
}
@@ -199,7 +210,7 @@ export default function CenterDashboard() {
};
document.addEventListener('visibilitychange', onVis);
return () => document.removeEventListener('visibilitychange', onVis);
}, [user?.id, location.pathname, loadData]); // 只依赖 user.id,避免无限循环
}, [userId, location.pathname, loadData, user]); // ⚡ 使用 userId防重复通过 ref 判断
// 定时刷新实时行情(每分钟一次)
useEffect(() => {