完成以下练习题,要求如下:
- 在/router/index.ts中添加全局守卫
- 并在守卫中获取meta元信息,完成权限判定
参考答案:
// /router/index.ts
{
path: '/',
element: React.createElement(BeforeEach, null, React.createElement(App)),
meta: { auth: true },
children: [
{
path: 'index',
element: React.createElement(Index),
meta: { auth: true }
},
{
path: 'login',
element: React.createElement(Login),
meta: { auth: false }
}
]
}
// /component/BeforeEach/BeforEach.tsx
import React from 'react'
import { useLocation, matchRoutes, Navigate } from 'react-router-dom'
import { routes } from '../../router';
interface BeforeEachProps {
children: React.ReactNode
}
export default function BeforeEach(props: BeforeEachProps) {
const location = useLocation();
const matchs = matchRoutes(routes, location)
if(Array.isArray(matchs)){
const meta = matchs[matchs.length-1].route.meta
if(meta?.auth){
return <Navigate to="/login" />
}
}
return <div>{ props.children }</div>;
}