Umi 的路由跳转可以在配置文件中配置,但如果需要跳转的 path
路径不固定,就比较麻烦了。
还在 Umi 提供了运行时配置,可以通过 patchRoutes
方法在运行时对路由进行修改。
比如我要修改 redirect
为第一个有效的路由 path
。
在 app.tsx
中增加下面代码:
- export function patchRoutes({ routes }: { routes: IRoute[] }) {
- let pagesRoutes = routes[0].routes;
- const serverRoutes = buildRoutes(serviceRoutes);
- serverRoutes.map((route: any) => {
- pagesRoutes?.push(route);
- });
- // 修改重定向配置
- if (pagesRoutes && pagesRoutes[1] && pagesRoutes[1].routes) {
- pagesRoutes[0] = {
- ...pagesRoutes[0],
- path: '/',
- redirect: pagesRoutes[1].routes[0].path,
- };
- }
- routes[0].routes = pagesRoutes;
- }
其中 buildRoutes
是用来组织路由的:
- function buildRoutes(routes: any) {
- return (routes || []).map((route: any) => {
- if (route.children && route.children.length > 0) {
- return {
- path: route.component,
- name: route.title,
- icon: route.icon,
- // 精准匹配默认false
- exact: false,
- routes: buildRoutes(route.children),
- };
- }
- });
- }
可以根据自己的需要进行相应的修改。
未经允许不得转载:前端资源网 - w3h5 » Umi动态修改路由跳转redirect配置