# 默认路由展示与重定向路由与404处理
# 默认路由
在当前路由没有匹配成功的时候,添加一个默认的展示内容,这就是React中的默认路由。
children: [
// 默认路由
{
index: true,
element: <div>默认的内容</div>
},
{
path: 'foo',
element: <Foo />
},
{
path: 'bar',
element: <Bar />
}
]
当没有匹配到foo或bar的时候,会展示默认路由的内容,一旦匹配成功后,就会替换掉默认路由。
# 重定向路由
通过访问的URL跳转到另一个URL上,从而实现重定向的需求。
import { createBrowserRouter, createHashRouter, Navigate } from 'react-router-dom'
children: [
// 默认路由
{
index: true,
element: <Navigate to="/about/foo/123" />,
},
{
path: 'foo',
element: <Foo />
},
{
path: 'bar',
element: <Bar />
}
]
# 处理404页面
可以通过路由中自带的errorElement选项来完成全局404需求。
export const routes = [
{
path: '/',
element: <App />,
errorElement: <div>404</div>,
}
]
也可以通过path: '*'
来实现局部404需求。
export const routes = [
{
path: '/',
element: <App />
},
{
path: '*',
element: <div>404</div>
}
]
这种局部404,可以在二级路由下进行设置。