二级多级子路由时,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