效果图:
代码实现:
import React, { useEffect, useState } from 'react'
import { Menu } from 'antd';
import {useNavigate, useLocation} from 'react-router-dom'
// import { ReadOutlined, EditOutlined, DatabaseOutlined ,MailOutlined,AppstoreOutlined} from '@ant-design/icons';
import { menuTree } from '../request/api'
const { SubMenu } = Menu;
// const { Sider } = Layout;
export default function Aside() {
const navigate = useNavigate()
const location = useLocation()
const [defaultKey, setDefaultKey] = useState('')
const [list,menuList] = useState([])
// 请求封装
const getList = () => {
let id = localStorage.getItem('id');
menuTree({id}).then(res=>{
menuList(res.data);
})
}
// 请求列表数据 componentDidMount
useEffect(() => {
getList()
}, [])
// 一般加个空数组就是为了模仿componentDidMounted
useEffect(()=>{
let path = location.pathname=="/"?"/first/first":location.pathname;
console.log(path,"path");
setDefaultKey(path);
}, [location.pathname])
const handleClick = (e) => {
navigate(e.key)
setDefaultKey(e.key)
};
return (
<Menu
className='menuList'
onClick={handleClick}
style={{ width: 240 }}
selectedKeys={[defaultKey]}
theme="dark"
mode="inline">
{
list.map(item=>{
if(item.childMenu.length>0){
return <SubMenu key={'/'+item.url} title={item.name}>
{
item.childMenu.map(node=>{
return <Menu.Item key={'/'+node.url}>{node.name}</Menu.Item>
})
}
</SubMenu>
}
return <Menu.Item key={'/'+item.url}>{item.name}</Menu.Item>
})
}
</Menu>
)
}
版权声明:本文为SmartJunTao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。