问题:用户必须登录才能访问后台首页。
思路:
创建 AuthRoute
组件,判断是否登录
1 登录直接显示要访问的页面
2 没有登录跳转到登录页面
难点:react中没有导航守卫,需要自己封装
第一步:首先要在components(公用组件)文件下,封装一个名为AuthRoute.js的组件
/* eslint-disable react/prop-types */
import { hasToken } from '@/utils/storage'
import { Redirect, Route } from 'react-router'
export default function AuthRoute (props) {
console.log(props)
const Com = props.component
return (
<Route
path={props.path}
render={() => {
if (hasToken()) {
return <Com />
} else {
console.log('没有token...')
return <Redirect to="/login" />
}
}}
/>
)
}
第二步:在APP.js文件中 导入
import AuthRoute from './components/AuthRouter'