From 712fc013f50c44928978b6bbaea631a4bd3685ee Mon Sep 17 00:00:00 2001 From: Jerry Yan <792602257@qq.com> Date: Wed, 21 Jan 2026 13:26:39 +0800 Subject: [PATCH] =?UTF-8?q?refactor(Sidebar):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E4=BE=A7=E8=BE=B9=E6=A0=8F=E8=8F=9C=E5=8D=95=E6=BF=80=E6=B4=BB?= =?UTF-8?q?=E9=A1=B9=E5=88=9D=E5=A7=8B=E5=8C=96=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加 useCallback 包装 initActiveItem 函数以提升性能 - 引入 isPathMatch 工具函数替代简单的路径匹配逻辑 - 重构菜单项遍历逻辑,使用 for...of 循环替代 forEach - 修复路径匹配逻辑,统一处理 /data/ 路径前缀 - 移除未使用的 Sparkles 图标导入 - 更新 useEffect 依赖数组以 --- frontend/src/pages/Layout/Sidebar.tsx | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/frontend/src/pages/Layout/Sidebar.tsx b/frontend/src/pages/Layout/Sidebar.tsx index 14b4fe1..a739f55 100644 --- a/frontend/src/pages/Layout/Sidebar.tsx +++ b/frontend/src/pages/Layout/Sidebar.tsx @@ -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) => {