1.patchRoutes({routes})
export function patchRoutes({ routes }:any) {
console.log(routes);
routes.unshift({
path: '/foo',
exact: true,
component: require('@/pages/login').default,
})
console.log('更新添加后的路由',routes);
}
2.根据服务器端动态生成路由
//定义额外路由变量
let extraRoutes:any[]
export function patchRoutes({ routes }:any) {
//合并服务端返回路由
extraRoutes.map(item=>{
routes.unshift({
path: item.path,
component: require(`@/pages${item.component}`).default,
})
})
}
//覆写render,会在patchRoutes之前执行
export function render(oldRender:any) {
// fetch('/api/routes').then(res=>res.json()).then((res) => {
// extraRoutes = res.routes;
// })
//模拟从服务端请求的获得的路由
extraRoutes=[
{path:'/serve',component:'/serve'}
]
oldRender();
}
3.render(oldRender: Function)
覆写 render。 比如用于渲染之前做权限校验,
import {history} from 'umi'
//定义额外路由变量
let extraRoutes:any[]
export function patchRoutes({ routes }:any) {
//合并服务端返回路由
extraRoutes.map(item=>{
routes.unshift({
path: item.path,
component: require(`@/pages${item.component}`).default,
})
})
}
//覆写render,会在patchRoutes之前执行
export function render(oldRender:any) {
// fetch('/api/routes').then(res=>res.json()).then((res) => {
// extraRoutes = res.routes;
// })
//模拟从服务端请求的获得的路由
extraRoutes=[
{path:'/serve',component:'/serve'}
]
//在渲染之前做一些校验,登录权限判断
const isLogin=true
if(isLogin){
history.push('/login')
}
oldRender();
}
4.onRouteChange({routes, matchedRoutes, location, action})
//做埋点统计
// export function onRouteChange({ location, routes, action }:any) {
// console.log(location);
// console.log(routes);
// console.log(action);
// }
//设置标题
export function onRouteChange({ matchedRoutes }:any):void {
console.log(matchedRoutes[matchedRoutes.length - 1].route);
if (matchedRoutes.length) {
document.title = matchedRoutes[matchedRoutes.length - 1].route.path || '';
}
}