困扰我好多天的自定义菜单及路由终于完成了,首先虽然看似为一个功能,但在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配置的路转就可以删除了。文章来源:https://www.toymoban.com/news/detail-674196.html
所以修改的代码如下:文章来源地址https://www.toymoban.com/news/detail-674196.html
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;
}
},
.......
};
};
到了这里,关于ant design pro + umi4的动态菜单与动态路由的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!