假设当前页面的路由为 /dashboard/analysis/realtime,
希望可以同时匹配到 [‘/dashboard’, ‘/dashboard/analysis’, ‘/dashboard/analysis/realtime’]
页面路径 path,不可以重复;用户在点击菜单项时,可以跳转到对应的页面
缺点:
- 对于 /realtime 这样的子路由,只根据当前的 pathname 去匹配菜单项中 path 属性的话,是匹配不到高亮的菜单;
- 怎样才能同时匹配到「分析页」与「仪表盘」的父路径
- 要用到2个函数
- urlToList
- getFlatMenuKeys ```jsx const menuData = [{ name: ‘仪表盘’, icon: ‘dashboard’, path: ‘/dashboard’, children: [{ name: ‘分析页’, path: ‘/dashboard/analysis’, children: [{ name: ‘实时数据’, path: ‘/dashboard/analysis/realtime’, }, { name: ‘离线数据’, path: ‘/dashboard/analysis/offline’, }], }], }];
<a name="k5P6r"></a>## urlToListurlToList返回不同级别的菜单数组假设当前页面的路由为 /dashboard/analysis/realtime,<br />返回的数组为 ['/dashboard', '/dashboard/analysis', '/dashboard/analysis/realtime']- 将这三个值 ['/dashboard', '/dashboard/analysis', '/dashboard/analysis/realtime'], 分别与菜单数据中的 path 属性 location.pathname 进行匹配,- 就可以一次性地匹配到所有当前页面应当被高亮的菜单项```jsxexport function urlToList(url) {if (typeof url !== 'string') return [];const urlList = url.split('/').filter(i => i);return urlList.map((urlItem, index) => {return `/${urlList.slice(0, index + 1).join('/')}`;});}
getFlatMenuKeys
虽然菜单项中的 path 一般都是普通字符串,有些特殊的路由也可能是正则的形式
如 /outlets/:id,在对二者进行匹配时
需要引入 path-to-regexp 库来处理,类似 /detail/23 和 /detail/:id 这样的路径
因为初始时菜单数据是树形结构的,不利于进行 path 属性的匹配,
还需要先将树形结构的菜单数据扁平化,然后再传入 getMeunMatchKeys 中
通过 getMeunMatchKeys 获取到 selectedKeys
export function getFlatMenuKeys(menuData) {return menuData.reduce((keys, item) => {const { children, path } = item;keys.push(path);if (children && children.length) {return keys.concat(getFlatMenuKeys(children));}return keys;}, []);}export function getMenuMatchKeys(flatMenuKeys, paths) {return paths.reduce((matchKeys, path) => {const filterPath = flatMenuKeys.filter(item => {return pathToRegexp(item).test(path);});return matchKeys.concat(filterPath);}, []);}
path是正则
因为初始时菜单数据是树形结构的,不利于进行 path 属性的匹配,所以还需要先将树形结构的菜单数据扁平化,然后再传入 getMeunMatchKeys 中
