最近在搭建react+antd的后台管理系统模板,碰到面包屑组件,需要根据左侧菜单栏当前选中的数据,再往上查找所有的父节点数据,即可使用下面这种方法返回正确的数据,真实业务场景中这种情况也不少见。废话不多说,直接上代码,CV即可用
1、 测试数据
// 测试数据
const routes = [
{
path: "/init",
element: 'init/index',
isParent: true,
meta: {
title: '初始也没',
icon: 'AppstoreOutlined',
keepAlive: false,
hiddenInMenu: false,
hideChildrenInMenu: false,
},
children: [
{
path: "/init/test",
element: "init/index",
meta: {
title: '测试子菜单',
icon: '',
keepAlive: false,
hiddenInMenu: false,
hideChildrenInMenu: true
},
}
]
},
{
path: "/home",
element: 'home/index',
isParent: true,
meta: {
title: 'home页面',
icon: 'AppstoreOutlined',
keepAlive: false,
hiddenInMenu: false,
hideChildrenInMenu: false,
},
children: [
{
path: "/home/test",
element: "home/index",
meta: {
title: '测试home子菜单',
icon: '',
keepAlive: false,
hiddenInMenu: false,
hideChildrenInMenu: true
},
}
]
},
]
2、封装工具函数
// 封装工具函数
const formatBreadcrumbRoutes = (routes, fn, result = []) => {
if (!routes) return []
for (const data of routes) {
result.push(data.path) // 这里时最终返回的数组列表,我取的是path路径
if (fn(data)) return result
if (data.children) {
const findChildren = formatBreadcrumbRoutes(data.children, fn, result)
if (findChildren.length) return findChildren
}
result.pop()
}
//走到这说明没找到目标
return []
}
3、测试
formatBreadcrumbRoutes(routes, data => data.path === '/init/test')
测试返回结果: