From be46997fe26f2226926cf68bd42538c63221adcf Mon Sep 17 00:00:00 2001 From: Junyan Qin Date: Sat, 10 May 2025 11:46:23 +0800 Subject: [PATCH] fix: bug when refresh page --- .../components/home-sidebar/HomeSidebar.tsx | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/web/src/app/home/components/home-sidebar/HomeSidebar.tsx b/web/src/app/home/components/home-sidebar/HomeSidebar.tsx index 00beaf04..848813c0 100644 --- a/web/src/app/home/components/home-sidebar/HomeSidebar.tsx +++ b/web/src/app/home/components/home-sidebar/HomeSidebar.tsx @@ -24,9 +24,7 @@ export default function HomeSidebar({ handleRouteChange(pathname); }, [pathname]); - const [selectedChild, setSelectedChild] = useState( - sidebarConfigList[0], - ); + const [selectedChild, setSelectedChild] = useState(); useEffect(() => { console.log('HomeSidebar挂载完成'); @@ -42,7 +40,17 @@ export default function HomeSidebar({ } function initSelect() { - handleChildClick(sidebarConfigList[0]); + // 根据当前路径选择对应的菜单项 + const currentPath = pathname; + const matchedChild = sidebarConfigList.find( + (childConfig) => childConfig.route === currentPath, + ); + if (matchedChild) { + handleChildClick(matchedChild); + } else { + // 如果没有匹配的路径,则默认选择第一个 + handleChildClick(sidebarConfigList[0]); + } } function handleRoute(child: SidebarChildVO) { @@ -98,7 +106,10 @@ export default function HomeSidebar({ > {}} - isSelected={selectedChild.id === config.id} + isSelected={ + selectedChild !== undefined && + selectedChild.id === config.id + } icon={config.icon} name={config.name} />