一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第6天,点击查看活动详情。
我们知道在react中是没有路由守卫的,但是类似的功能有现成的。
参考文献v5.reactrouter.com/web/example…
我们在日常开发中想要使用的方便,可以自己封装一个鉴权路由组件
1、定义私有路由组件。在 components 目录中创建 PrivateRoute路由组件:实现路由的登录访问控制逻辑
其中判断的依据是:
- 有token,正常访问
- 没有token,重定向到登录页面,并传递要访问的路由地址
2、定义核心代码
在components/PrivateRoute.tsx 中:
import { hasToken } from '@/utils/storage'
import { Route, Redirect, RouteProps } from 'react-router-dom'
// { children, ...rest },这里是把children结构出来,其他的属性一起放到rest里
export const PrivateRoute = ({ children, ...rest }: RouteProps) => {
return (
<Route
//再将其他的属性,设置给Route,{...rest}里包括有computedMatch、location、path等一些其他的路由参数
{...rest}里包括有
// reder函数里的参数props,可以拿到所有的属性
render={props => {
if (hasToken()) {
return children
}
return (
<Redirect
to={{
pathname: '/login',
state: {
from: props.location.pathname // 回跳地址
}
}}
/>
)
}}
/>
)
}
3、在对应的组件中使用
import { PrivateRoute } from '@/components/PrivateRoute'
const App = () => {
return (
// ...
<PrivateRoute path="/profile/edit"> //路径
<ProfileEdit /> //需要展示的组件,也可以写在component里面
</PrivateRoute>
)
}