refactor: clean up MainLayout component and improve authentication handling

This commit is contained in:
ShiYu
2025-05-19 16:56:43 +08:00
parent 4085c2329e
commit d326970e8d
+16 -23
View File
@@ -1,21 +1,20 @@
import { useState, useEffect } from 'react';
import { Outlet, useNavigate, useLocation, matchPath } from 'react-router';
import { Layout, theme } from 'antd';
import { clearAuthData, getStoredUser, isAuthenticated } from '../api';
import {useState, useEffect} from 'react';
import {Outlet, useNavigate, useLocation, matchPath} from 'react-router';
import {Layout, theme} from 'antd';
import {clearAuthData, isAuthenticated} from '../api';
import useIsMobile from '../hooks/useIsMobile';
import {useAuth} from '../api/AuthContext';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import Footer from './components/Footer';
import routes, { type RouteConfig } from '../config/routeConfig';
import routes, {type RouteConfig} from '../config/routeConfig';
const { Content } = Layout;
const {Content} = Layout;
function MainLayout() {
const {refreshUser} = useAuth();
const isMobile = useIsMobile();
const [collapsed, setCollapsed] = useState(isMobile); // 移动设备默认折叠侧边栏
// 重命名避免未使用警告,或用于未来扩展
const [, setUser] = useState<any>(null);
const [collapsed, setCollapsed] = useState(isMobile);
const [currentRouteData, setCurrentRouteData] = useState<{
routeInfo: RouteConfig | undefined;
params: Record<string, string>;
@@ -29,7 +28,7 @@ function MainLayout() {
const location = useLocation();
const {
token: { colorBgContainer },
token: {colorBgContainer},
} = theme.useToken();
// 查找当前路由信息
@@ -39,7 +38,7 @@ function MainLayout() {
// 测试每个路由是否匹配当前路径
for (const route of routes) {
const match = matchPath(
{ path: `/${route.path}`, end: true },
{path: `/${route.path}`, end: true},
pathname
);
@@ -64,7 +63,7 @@ function MainLayout() {
if (pathname.startsWith(pattern)) {
const match = matchPath(
{ path: `/${route.path}`, end: false },
{path: `/${route.path}`, end: false},
pathname
);
@@ -93,11 +92,8 @@ function MainLayout() {
navigate('/login');
return;
}
const storedUser = getStoredUser();
if (storedUser) {
setUser(storedUser);
}
}, [navigate]);
refreshUser();
}, [navigate, refreshUser]);
// 监听路由变化,更新当前路由信息
useEffect(() => {
@@ -162,15 +158,12 @@ function MainLayout() {
}}>
{/* 渲染子路由组件 */}
<Outlet context={{
updateBreadcrumbTitle: (title: string) => {
setCurrentRouteData(prev => ({ ...prev, title }));
},
isMobile
}} />
}}/>
</div>
</Content>
{/* 页脚组件 */}
<Footer isMobile={isMobile} />
<Footer isMobile={isMobile}/>
</Layout>
</Layout>
);