封装一个AuthRoute路由拦截组件,如果有token直接跳转,如果没有token 返回到登陆页面
import { Route, Redirect } from 'react-router-dom'
import { isAuth } from '../../utils'
//...剩余参数, 吧所有参数收集到一个数组或对象中,吧component单独拿出来
const AuthRoute = ({ component: Component, ...rest }) => {
console.log({ ...rest })
return <Route {...rest}
render={(props) => {
//判断是否登陆
const auth = isAuth()
if (auth) {
//有token登陆成功 跳转
//标签首字母需要大写,重命名component
return <Component></Component>
} else {
//没有token没有登陆 重定向到登陆页面 并吧路由带过去
// console.log(props.location.pathname)
return <Redirect to={{
pathname: '/login',
state: { from: props.location.pathname }
}}></Redirect>
}
}}
></Route>
}
export default AuthRoute