二级多级子路由时,react面包屑获取及处理
因react-router中路由配置时,子路由为父级路由+子路由拼接而成,故当实现面包屑时需要根据当前路由获取完整的父子路由链
入参:如 /layout/list/showList
出参:如 ['/layout', '/layout/list', '/layout/list/showList']
import { Breadcrumb } from 'antd';
import { Link, useLocation } from 'react-router-dom';
const location = useLocation(); console.log('---00---', location.pathname) const pathSnippets = location.pathname.split('/').filter((i) => i); console.log('---11---', pathSnippets) const extraBreadcrumbItems = pathSnippets.map((_, index) => { const url = `/${pathSnippets.slice(0, index + 1).join('/')}`; console.log('---22---', url) return ( <Breadcrumb.Item key={url}> <Link to={url}>{url}</Link> </Breadcrumb.Item> ); }); console.log('---33---', extraBreadcrumbItems)
使用
<Breadcrumb separator='>'>{extraBreadcrumbItems}</Breadcrumb>
效果(名字未做更改,根据实际需要修改)
官方
https://ant.design/components/breadcrumb-cn
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步