pref: 优化 useEffect 依赖和清理逻辑
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
// src/views/Community/components/DynamicNewsCard.js
|
||||
// 横向滚动事件卡片组件(实时要闻·动态追踪)
|
||||
|
||||
import React, { forwardRef, useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import React, { forwardRef, useState, useEffect, useMemo, useCallback, useRef } from 'react';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import {
|
||||
Card,
|
||||
@@ -72,6 +72,9 @@ const DynamicNewsCard = forwardRef(({
|
||||
// 本地状态
|
||||
const [selectedEvent, setSelectedEvent] = useState(null);
|
||||
|
||||
// 初始化标记 - 确保初始加载只执行一次
|
||||
const hasInitialized = useRef(false);
|
||||
|
||||
// 使用分页 Hook
|
||||
const {
|
||||
currentPage,
|
||||
@@ -91,9 +94,10 @@ const DynamicNewsCard = forwardRef(({
|
||||
toast
|
||||
});
|
||||
|
||||
// 初始加载
|
||||
// 初始加载 - 只在组件首次挂载且未初始化时执行
|
||||
useEffect(() => {
|
||||
if (allCachedEvents.length === 0) {
|
||||
if (!hasInitialized.current && allCachedEvents.length === 0) {
|
||||
hasInitialized.current = true;
|
||||
dispatch(fetchDynamicNews({
|
||||
page: PAGINATION_CONFIG.INITIAL_PAGE,
|
||||
per_page: PAGINATION_CONFIG.CAROUSEL_PAGE_SIZE,
|
||||
@@ -103,12 +107,27 @@ const DynamicNewsCard = forwardRef(({
|
||||
}
|
||||
}, [dispatch, allCachedEvents.length]);
|
||||
|
||||
// 默认选中第一个事件
|
||||
// 默认选中第一个事件 - 只在当前选中的事件不在当前页时重置
|
||||
useEffect(() => {
|
||||
if (currentPageEvents.length > 0 && !selectedEvent) {
|
||||
setSelectedEvent(currentPageEvents[0]);
|
||||
if (currentPageEvents.length > 0) {
|
||||
// 检查当前选中的事件是否在当前页中
|
||||
const selectedEventInCurrentPage = currentPageEvents.find(
|
||||
e => e.id === selectedEvent?.id
|
||||
);
|
||||
|
||||
// 如果选中的事件不在当前页,则选中当前页第一个事件
|
||||
if (!selectedEventInCurrentPage) {
|
||||
setSelectedEvent(currentPageEvents[0]);
|
||||
}
|
||||
}
|
||||
}, [currentPageEvents, selectedEvent]);
|
||||
}, [currentPageEvents, selectedEvent?.id]);
|
||||
|
||||
// 组件卸载时清理选中状态
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setSelectedEvent(null);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Card ref={ref} {...rest} bg={cardBg} borderColor={borderColor} mb={4}>
|
||||
|
||||
Reference in New Issue
Block a user