ant design pro + umi4的动态菜单与动态路由
困扰我好多天的自定义菜单及路由终于完成了,首先虽然看似为一个功能,但在umi4中是两项配置。
先说说我浪费了大量时间使用的处理方式:因为曾经的项目是umi3的,所以我就想原样搬过来,结果发现,布局页BasicLayout的子children不见了!
如果这个子路由能正常显示,那引个ProLayout也就不用大费周章找其他方法。参考:https://blog.csdn.net/eisha2015/article/details/114831390
后来,我又找到了umi的patchRoutes,但发现怎么重写路由,菜单都没有变化。参考:https://blog.csdn.net/weixin_43294560/article/details/107447241
最后还是翻到ProComponents菜单的高级用法,才发现菜单直接在app.tsx里配置就行了,相当于这个文件就是当初的ProLayout。
之后还将子路由routes为[]时,把父结点也清除的数据处理,以及使用patchClientRoutes来修改默认路由跳转,而原本routes.ts配置的路转就可以删除了。
所以修改的代码如下:
type Router = {
name?: string,
path: string,
icon?: string | React.ReactNode,
routes?: Router[],
component?: string,
redirect?: string,
}
// routes为[],则删除结点
const deleteroutes = (arr: Router[]) => {
let childs = arr
for (let i = childs.length; i--; i > 0) {
const routes = childs[i].routes;
if (routes) {
if (routes.length) {
// 处理antd的图标,全部引入包的大小爆增,不如用iconfontUrl
// const icon = childs[i].icon;
// if (typeof icon === 'string') {
// childs[i].icon = React.createElement(Icons[icon]);
// }
deleteroutes(routes);
} else {
delete childs[i];
}
}
}
return JSON.parse(JSON.stringify(arr).replace(/null,/g, '').replace(/,null/g, '')) as Router[];
}
let extraRoutes: Router[];
export const patchClientRoutes = ({ routes }: any) => {
const r = extraRoutes;
const to = r![0].routes![0].routes![0].path;
routes.unshift({
path: '/',
element: <Navigate to={to || ''} replace />,
});
r.forEach(element => {
routes.unshift({
path: element.path,
element: <Navigate to={element.routes![0].routes![0].path} replace />,
});
});
};
export function render(oldRender: any) {
setTimeout(() => {
extraRoutes = deleteroutes([{
name: '一级菜单A',
path: '/a',
routes: [
{
name: '二级菜单AA',
path: '/a/aa',
icon: 'icon1',
routes: [
],
},
{
name: '二级菜单BB',
path: '/a/bb',
icon: 'icon2',
routes: [
{
name: '三级菜单AAA',
path: '/a/aa/aaa',
component: './a/aa/aaa',
},
{
name: '三级菜单BBB',
path: '/a/aa/bbb',
component: './a/aa/bbb',
},
],
},
]
},
{
name: '一级菜单B',
path: '/b',
routes: [
],
}]);
oldRender();
}, 1000);
}
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
return {
menu: {
// 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
// params: {
// userId: initialState?.currentUser?.userid,
// },
request: async (params, defaultMenuData) => {
return extraRoutes;
}
},
.......
};
};