refactor(Sidebar): 优化侧边栏菜单激活项初始化逻辑

- 添加 useCallback 包装 initActiveItem 函数以提升性能
- 引入 isPathMatch 工具函数替代简单的路径匹配逻辑
- 重构菜单项遍历逻辑,使用 for...of 循环替代 forEach
- 修复路径匹配逻辑,统一处理 /data/ 路径前缀
- 移除未使用的 Sparkles 图标导入
- 更新 useEffect 依赖数组以
This commit is contained in:
2026-01-21 13:26:39 +08:00
parent 34fa184b69
commit 712fc013f5

View File

@@ -1,11 +1,11 @@
import { memo, useEffect, useState } from "react";
import { memo, useCallback, useEffect, useState } from "react";
import { Button, Drawer, Menu, Popover } from "antd";
import {
CloseOutlined,
MenuOutlined,
SettingOutlined,
} from "@ant-design/icons";
import { ClipboardList, Sparkles, X } from "lucide-react";
import { ClipboardList, X } from "lucide-react";
import { menuItems } from "@/pages/Layout/menu";
import { NavLink, useLocation, useNavigate } from "react-router";
import TaskUpload from "./TaskUpload";
@@ -13,6 +13,9 @@ import SettingsPage from "../SettingsPage/SettingsPage";
import { useAppSelector, useAppDispatch } from "@/store/hooks";
import { showSettings, hideSettings } from "@/store/slices/settingsSlice";
const isPathMatch = (currentPath: string, targetPath: string) =>
currentPath === targetPath || currentPath.startsWith(`${targetPath}/`);
const AsiderAndHeaderLayout = () => {
const { pathname } = useLocation();
const navigate = useNavigate();
@@ -23,27 +26,27 @@ const AsiderAndHeaderLayout = () => {
const dispatch = useAppDispatch();
// Initialize active item based on current pathname
const initActiveItem = () => {
const initActiveItem = useCallback(() => {
const dataPath = pathname.startsWith("/data/") ? pathname.slice(6) : pathname;
for (let index = 0; index < menuItems.length; index++) {
const element = menuItems[index];
if (element.children) {
element.children.forEach((subItem) => {
if (pathname.includes(subItem.id)) {
for (const subItem of element.children) {
if (isPathMatch(dataPath, subItem.id)) {
setActiveItem(subItem.id);
return;
}
});
} else if (pathname.includes(element.id)) {
}
} else if (isPathMatch(dataPath, element.id)) {
setActiveItem(element.id);
return;
}
}
console.log(pathname);
};
}, [pathname]);
useEffect(() => {
initActiveItem();
}, [pathname]);
}, [initActiveItem]);
useEffect(() => {
const handleShowTaskPopover = (event: CustomEvent) => {