pref(layout): 使用useMemo对路由表进行预构建,避免因异步数据处理导致的闪烁问题(页面先跳转403后渲染正常)

master
钟良源 5 months ago
parent 37ff877c98
commit d1c6e94edf

@ -1,4 +1,4 @@
import React, { useState, ReactNode, useRef, useEffect } from 'react'; import React, { useState, ReactNode, useRef, useEffect, useMemo } from 'react';
import { Layout, Menu, Breadcrumb, Spin } from '@arco-design/web-react'; import { Layout, Menu, Breadcrumb, Spin } from '@arco-design/web-react';
import cs from 'classnames'; import cs from 'classnames';
import { import {
@ -114,14 +114,14 @@ function PageLayout({ children }: { children: ReactNode }) {
const paddingTop = showNavbar ? { paddingTop: navbarHeight } : {}; const paddingTop = showNavbar ? { paddingTop: navbarHeight } : {};
const paddingStyle = { ...paddingLeft, ...paddingTop }; const paddingStyle = { ...paddingLeft, ...paddingTop };
// 初始化时创建并实例路由映射 const routeMapMemo = useMemo(() => {
useEffect(() => { const map = new Map<string, ReactNode[]>();
// 仅构建 routeMap不渲染菜单
function buildRouteMap(_routes: IRoute[], parentNode = []) { function buildRouteMap(_routes: IRoute[], parentNode = []) {
_routes.forEach((route) => { _routes.forEach((route) => {
const { breadcrumb = true, ignore } = route; const { breadcrumb = true, ignore } = route;
routeMap.current.set( map.set(
`/${route.key}`, `/${route.key}`,
breadcrumb ? [...parentNode, route.name] : [] breadcrumb ? [...parentNode, route.name] : []
); );
@ -129,7 +129,7 @@ function PageLayout({ children }: { children: ReactNode }) {
const visibleChildren = (route.children || []).filter((child) => { const visibleChildren = (route.children || []).filter((child) => {
const { ignore, breadcrumb = true } = child; const { ignore, breadcrumb = true } = child;
if (ignore || route.ignore) { if (ignore || route.ignore) {
routeMap.current.set( map.set(
`/${child.key}`, `/${child.key}`,
breadcrumb ? [...parentNode, route.name, child.name] : [] breadcrumb ? [...parentNode, route.name, child.name] : []
); );
@ -144,6 +144,7 @@ function PageLayout({ children }: { children: ReactNode }) {
} }
buildRouteMap(routes); buildRouteMap(routes);
return map;
}, [routes]); }, [routes]);
function renderRoutes(locale) { function renderRoutes(locale) {
@ -217,7 +218,7 @@ function PageLayout({ children }: { children: ReactNode }) {
} }
useEffect(() => { useEffect(() => {
const routeConfig = routeMap.current.get(pathname); const routeConfig = routeMapMemo.get(pathname);
setBreadCrumb(routeConfig || []); setBreadCrumb(routeConfig || []);
updateMenuStatus(); updateMenuStatus();
}, [pathname]); }, [pathname]);
@ -279,7 +280,7 @@ function PageLayout({ children }: { children: ReactNode }) {
</div> </div>
)} )}
<Content> <Content>
{routeMap.current.has(pathname) ? children : <NoAccess />} {routeMapMemo.has(pathname) ? children : <NoAccess />}
</Content> </Content>
</div> </div>
{/*{showFooter && <Footer />}*/} {/*{showFooter && <Footer />}*/}

Loading…
Cancel
Save