Umi动态修改路由跳转redirect配置

Umi 的路由跳转可以在配置文件中配置,但如果需要跳转的 path 路径不固定,就比较麻烦了。

还在 Umi 提供了运行时配置,可以通过 patchRoutes 方法在运行时对路由进行修改。

比如我要修改 redirect 为第一个有效的路由 path 。

app.tsx 中增加下面代码:

  1. export function patchRoutes({ routes }: { routes: IRoute[] }) {
  2.   let pagesRoutes = routes[0].routes;
  3.   const serverRoutes = buildRoutes(serviceRoutes);
  4.   serverRoutes.map((route: any) => {
  5.     pagesRoutes?.push(route);
  6.   });
  7.   // 修改重定向配置
  8.   if (pagesRoutes && pagesRoutes[1] && pagesRoutes[1].routes) {
  9.     pagesRoutes[0] = {
  10.       ...pagesRoutes[0],
  11.       path: '/',
  12.       redirect: pagesRoutes[1].routes[0].path,
  13.     };
  14.   }
  15.   routes[0].routes = pagesRoutes;
  16. }

其中 buildRoutes 是用来组织路由的:

  1. function buildRoutes(routes: any) {
  2.   return (routes || []).map((route: any) => {
  3.     if (route.children && route.children.length > 0) {
  4.       return {
  5.         path: route.component,
  6.         name: route.title,
  7.         icon: route.icon,
  8.         // 精准匹配默认false
  9.         exact: false,
  10.         routes: buildRoutes(route.children),
  11.       };
  12.     }
  13.   });
  14. }

可以根据自己的需要进行相应的修改。

未经允许不得转载:前端资源网 - w3h5 » Umi动态修改路由跳转redirect配置

赞 (1)
分享到: +

评论 沙发

Avatar

换个身份

  • 昵称 (必填)
  • 邮箱 (选填)