文章轉自我的語雀:https://www.yuque.com/liuyin-zzwa0/ada6ao/qi3n6u
Ant Design Pro 使用了 umi.js(中文名: 烏米)進行頁面路由管理
在 router.config.js 中使用了配置式的路由
export default {
routes: [
{ path: '/', component: './a' },
{ path: '/users',
routes: [
{ path: '/users/detail', component: './users/detail' },
{ path: '/users/:id', component: './users/id' }
]
},
],
};
上面的代碼就會帶來嵌套路由,在瀏覽器中輸入 /users 時,項目會自動定位到 component: './users/index' 中,但由于page/users/
中無該組件,會導致頁面出現404或者空白。
解決辦法有兩種
- 已經確定實際要渲染的頁面
直接在 routes 中添加一個重定向的路由
{ path: '/users', component: './users/_layout',
routes: [
{ path: '/users', redirect: '/users/detail', },
{ path: '/users/detail', component: './users/detail' },
{ path: '/users/:id', component: './users/id' }
]
},
- 在頁面中才能確定的路由
在頁面中使用 router.replace 進行重定向
{ path: '/users', component: './users/_layout',
routes: [
{ path: '/users/detail', component: './users/detail' },
{ path: '/users/:id', component: './users/id' }
{ path: '/users/:id/settings', component: './users/settings' }
]
},
此時在 settings.js
中
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
class Layout extends PureComponent {
pageRedirect = () => {
const { match: { url, params }, location: { pathname, query, search } } = this.props;
if(url == pathname){
router.replace(`${url.replace(/\/$/, '')}/settings${search}`)
}
}
componentDidMount(){
this.pageRedirect();
}
componentDidUpdate(){
this.pageRedirect();
}
render(){
const { match: { url }, location: { pathname }, children } = this.props;
const isRoot = url == pathname;
return(
<div>
<div>這是layout</div>
<div>
{isRoot ? null : children} // 防止未指定時渲染出 umi的404
</div>
</div>
);
}
}
FQA: 為什么 componentDidMount 中也要調用 pageRedirect 這個方法呢?
因為該組件在初始化及整個生命周期中沒有 props
跟 state
的更改,也就不會有頁面的重新 render,會導致 componentDidUpdate 無法被觸發,若是能確定在組件的生命周期中會重新觸發 render , componentDidMount 中可以不執行 pageRedirect 方法
特殊情況也會出現 404
例如下面這種寫法:
{
path: '/reception',
name: 'reception',
icon: 'schedule',
authority: ['admin', 'user'],
routes: [
{
path: '/reception/',
name: 'list',
component: './Reception/ReceptionSchemeList',
hideInMenu: true,
},
{
path: '/reception/:receptionGroupId',
name: 'detail',
component: './Reception/ReceptionScheme/Index',
hideInMenu: true,
},
{
path: '/reception/company/:structureId',
component: './Reception/Company/Index',
hideInMenu: true,
}
]
},
輸入 reception/company/123
后,會出現如下頁面:

image.png
這是因為 umi 優先匹配到 '/reception/:receptionGroupId'了 ,解決辦法是提高 '/reception/company/:structureId' 的優先級, 即鏈接的同級中,固定的一定要先于動態的。
{
path: '/reception/company/:structureId',
component: './Reception/Company/Index',
hideInMenu: true,
},
{
path: '/reception/:receptionGroupId',
name: 'detail',
component: './Reception/ReceptionScheme/Index',
hideInMenu: true,
},