侧边栏选中效果修复

This commit is contained in:
liamzi
2025-01-15 11:08:08 +08:00
parent 1eb2e0dd57
commit 3d7b8d705d
6 changed files with 31 additions and 14 deletions

View File

@@ -18,9 +18,7 @@ const Sidebar = ({ collapsed }) => {
if (!user?.id||user.menukeys?.length===0) return [];
return getMenuItems(user?.menukeys || []);
}, [user]);
useEffect(()=>{
console.log(menuClient,'menuClient');
},[menuClient])
const defaultOpenKeys = useMemo(() => {
const pathSegments = location.pathname.split("/").filter(Boolean);
return pathSegments.reduce((acc, _, index) => {
@@ -30,6 +28,10 @@ useEffect(()=>{
}, []);
}, [location.pathname]);
const selectedKey = useMemo(() => {
return location.pathname;
}, [location.pathname]);
const handleMenuClick = ({ key }) => {
navigate(key);
};
@@ -48,7 +50,7 @@ useEffect(()=>{
<Menu
theme={isDarkMode ? "dark" : "light"}
mode="inline"
selectedKeys={[location.pathname]}
selectedKeys={[selectedKey]}
defaultOpenKeys={defaultOpenKeys}
items={menuClient}
onClick={handleMenuClick}

View File

@@ -2,7 +2,7 @@ import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
const PUBLIC_PATHS = ['login', '404'];
const PUBLIC_PATHS = ['login', '404','home'];
export const ProtectedRoute = ({ children }) => {
const { user } = useAuth();
const location = useLocation();
@@ -16,12 +16,11 @@ export const ProtectedRoute = ({ children }) => {
});
if (!hasPermission) {
return <Navigate to="/404" replace />;
return <Navigate to="/home" replace />;
}
return children;
}
// 如果用户未登录,重定向到登录页
return <Navigate to="/login" state={{ from: location }} replace />;
};

11
src/pages/home/index.jsx Normal file
View File

@@ -0,0 +1,11 @@
import React from 'react';
const Home = () => {
return (
<div>
首页
</div>
);
};
export default Home;

View File

@@ -68,8 +68,8 @@ const AppRoutes = () => {
<Route
path="/login"
element={
user?.id && user.menukeys?.includes('company/serviceTemplate') ? (
<Navigate to="/company/serviceTemplate" replace />
user?.id ? (
<Navigate to="/home" replace />
) : (
<Login />
)
@@ -84,10 +84,9 @@ const AppRoutes = () => {
</ProtectedRoute>
}
>
{/* 默认重定向到服务管理页面 */}
<Route
index
element={<Navigate to="/company/serviceTemplate" replace />}
element={<Navigate to="/home" replace />}
/>
{renderRoutes(allRoutes)}
<Route path="*" element={<NotFound />} />

View File

@@ -1,7 +1,13 @@
import { lazy } from "react";
// 所有可用的路由配置
export const allRoutes = [
{
path: "/home",
component: lazy(() => import("@/pages/home")),
name: "首页",
hidden: true,
key: "home",
},
{
path: "dashboard",
component: lazy(() => import("@/pages/Dashboard")),

View File

@@ -39,7 +39,7 @@ const generateMenuItems = (routes, menuKeys = [], parentPath = "") => {
const icon = route.icon && <ColorIcon icon={getAntIcon(route.icon)} />;
const menuItem = {
key: route.key, // 使用 key 而不是 fullPath
key: fullPath,
icon,
label: route.name,
};