From 1004569bc0d0eca8d2c36ee0e7350b2c51ad7e75 Mon Sep 17 00:00:00 2001 From: ZLY Date: Wed, 20 Aug 2025 09:29:48 +0800 Subject: [PATCH] =?UTF-8?q?refactor(layout):=20=E4=BC=98=E5=8C=96=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E6=B8=B2=E6=9F=93=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将路由映射的构建过程移至 useEffect 中,仅在初始化时执行 -重构 renderRoutes 函数,分离路由映射构建和菜单渲染逻辑- 优化子路由的处理方式,提高代码可读性和性能 --- src/pages/layout.tsx | 42 +++++++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/src/pages/layout.tsx b/src/pages/layout.tsx index 8ba44cf..bc082b0 100644 --- a/src/pages/layout.tsx +++ b/src/pages/layout.tsx @@ -103,17 +103,12 @@ function PageLayout({ children }: { children: ReactNode }) { const paddingTop = showNavbar ? { paddingTop: navbarHeight } : {}; const paddingStyle = { ...paddingLeft, ...paddingTop }; - function renderRoutes(locale) { - routeMap.current.clear(); - return function travel(_routes: IRoute[], level, parentNode = []) { - return _routes.map((route) => { + // 初始化时创建并实例路由映射 + useEffect(() => { + // 仅构建 routeMap,不渲染菜单 + function buildRouteMap(_routes: IRoute[], parentNode = []) { + _routes.forEach((route) => { const { breadcrumb = true, ignore } = route; - const iconDom = getIconFromKey(route.key); - const titleDom = ( - <> - {iconDom} {locale[route.name] || route.name} - - ); routeMap.current.set( `/${route.key}`, @@ -128,13 +123,37 @@ function PageLayout({ children }: { children: ReactNode }) { breadcrumb ? [...parentNode, route.name, child.name] : [] ); } - return !ignore; }); + if (!ignore && visibleChildren.length) { + buildRouteMap(visibleChildren, [...parentNode, route.name]); + } + }); + } + + buildRouteMap(routes); + }, [routes]); + + function renderRoutes(locale) { + return function travel(_routes: IRoute[], level, parentNode = []) { + return _routes.map((route) => { + const { ignore } = route; + const iconDom = getIconFromKey(route.key); + const titleDom = ( + <> + {iconDom} {locale[route.name] || route.name} + + ); + + const visibleChildren = (route.children || []).filter((child) => { + return !child.ignore; + }); + if (ignore) { return ''; } + if (visibleChildren.length) { menuMap.current.set(route.key, { subMenu: true }); return ( @@ -143,6 +162,7 @@ function PageLayout({ children }: { children: ReactNode }) { ); } + menuMap.current.set(route.key, { menuItem: true }); return (