在src下创建app.tsx文件

1.patchRoutes({routes})

  1. export function patchRoutes({ routes }:any) {
  2. console.log(routes);
  3. routes.unshift({
  4. path: '/foo',
  5. exact: true,
  6. component: require('@/pages/login').default,
  7. })
  8. console.log('更新添加后的路由',routes);
  9. }

image.png 2.根据服务器端动态生成路由

  1. //定义额外路由变量
  2. let extraRoutes:any[]
  3. export function patchRoutes({ routes }:any) {
  4. //合并服务端返回路由
  5. extraRoutes.map(item=>{
  6. routes.unshift({
  7. path: item.path,
  8. component: require(`@/pages${item.component}`).default,
  9. })
  10. })
  11. }
  12. //覆写render,会在patchRoutes之前执行
  13. export function render(oldRender:any) {
  14. // fetch('/api/routes').then(res=>res.json()).then((res) => {
  15. // extraRoutes = res.routes;
  16. // })
  17. //模拟从服务端请求的获得的路由
  18. extraRoutes=[
  19. {path:'/serve',component:'/serve'}
  20. ]
  21. oldRender();
  22. }

3.render(oldRender: Function)

覆写 render。 比如用于渲染之前做权限校验,

  1. import {history} from 'umi'
  2. //定义额外路由变量
  3. let extraRoutes:any[]
  4. export function patchRoutes({ routes }:any) {
  5. //合并服务端返回路由
  6. extraRoutes.map(item=>{
  7. routes.unshift({
  8. path: item.path,
  9. component: require(`@/pages${item.component}`).default,
  10. })
  11. })
  12. }
  13. //覆写render,会在patchRoutes之前执行
  14. export function render(oldRender:any) {
  15. // fetch('/api/routes').then(res=>res.json()).then((res) => {
  16. // extraRoutes = res.routes;
  17. // })
  18. //模拟从服务端请求的获得的路由
  19. extraRoutes=[
  20. {path:'/serve',component:'/serve'}
  21. ]
  22. //在渲染之前做一些校验,登录权限判断
  23. const isLogin=true
  24. if(isLogin){
  25. history.push('/login')
  26. }
  27. oldRender();
  28. }

4.onRouteChange({routes, matchedRoutes, location, action})

  1. //做埋点统计
  2. // export function onRouteChange({ location, routes, action }:any) {
  3. // console.log(location);
  4. // console.log(routes);
  5. // console.log(action);
  6. // }
  7. //设置标题
  8. export function onRouteChange({ matchedRoutes }:any):void {
  9. console.log(matchedRoutes[matchedRoutes.length - 1].route);
  10. if (matchedRoutes.length) {
  11. document.title = matchedRoutes[matchedRoutes.length - 1].route.path || '';
  12. }
  13. }