选中一个二级菜单节点的时候,刷新页面的时候应该保持用户之前的选中状态,并且二级菜单展开项应该默认展开。
刷新页面选中应该不会改变,以下代码可以直接实现
Router/index.js
import React, { lazy } from "react"
//重定向
import { Navigate } from "react-router-dom"
import Home from "@/view/Home"
//路由懒加载
const Page1 = lazy(() => import("@/components/Page1/index"))
const Page2 = lazy(() => import("@/components/Page2/index"))
const Page301 = lazy(() => import("@/components/Page31/index"))
//懒加载 提成一个公共函数,规定类型,只需调用就可以了
const Loading = (component: JSX.Element) => {
return (
Loading...
Home主页面
import React, { useState, useEffect } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
import {
DesktopOutlined,
FileOutlined,
PieChartOutlined,
TeamOutlined,
UserOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Breadcrumb, Layout, Menu, theme } from 'antd';
const { Header, Content, Footer, Sider } = Layout;
type MenuItem = Required['items'][number];
export default function Home() {
//items控制的是左侧的侧边栏,也可以单独给这块提出单独的组件用来控制侧边栏
const items: MenuItem[] = [
{
label:'Page1',
key: '/page1',
icon: ,
},
{
label:'Page2',
key: '/page2',
icon: ,
},
{
label:'Page3',
key: 'page3',
icon: ,
children:[
{
label:'Page3-1',
key: '/page3/page301',
},
{
label:'Page3-2',
key: '/page3/page302',
},
{
label:'Page3-3',
key: '/page3/page303',
},
]
},
{
label:'Page4',
key: 'page4',
icon: ,
children:[
{
label:'Page4-1',
key: '/page4/page401',
},
{
label:'Page4-2',
key: '/page4/page402',
}
]
},
{
label:'Page5',
key: '/page5',
icon: ,
}
];
const {
token: { colorBgContainer },
} = theme.useToken();
const [collapsed, setCollapsed] = useState(false);
//跳转
const NavigateTo = useNavigate()
//侧边栏切换 :获取items里第二个参数地址信息,通过useNavigate配合点击事件实现点击切换页面
const MenuClick = (e: any) => {
NavigateTo(e.key)
}
//-----------------------------------
//刷新通过useLocation获取地址栏,判断路径,定到选择项
//刷新问题:刷新选中项不会变,之前打开的展开项也不会收缩
const { pathname } = useLocation()
let firstOpenKey:string=""
function findkey(obj:any){
return obj.key===pathname
}
//判断有没有['children'] 有就直接拿到里面的key
for(let i=0;i0 && items[i]['children'].find(findkey)){
firstOpenKey=items[i].key
break
}
}
//展开项的初始值,刷新之后不会收缩
const [openKeys, setOpenKeys] = useState([firstOpenKey]);
const onOpenChange = (keys: any) => {
setOpenKeys([keys[keys.length-1]])
}
//-----------------------------------
return (
{/* 左边侧边栏 */}
setCollapsed(value)}>
{/* 右边内容区 */}
{/* 顶部 上方面包屑 */}
User
Bill
{/* 内容区 */}
{/* 底部区 */}
)
}