【发布时间】:2022-12-13 21:17:40
【问题描述】:
我正在尝试使用 react-router v6 在 react 中构建我的身份验证逻辑 当我运行下面的代码时,我发现了一些奇怪的事情是我的代码
import React from 'react';
import useStore from '../../../store/store';
import { useEffect } from 'react';
import {useNavigate,redirect } from 'react-router-dom';
export default function (SpecificComponent, option, adminRoute = null) {
const navigate = useNavigate();
const {auth,accessToken}= useStore();
// option = null // pages taht anyone can access
// option = true // pages that only loginuser can access
// option = false // pages that loginuser can not access
// option = true ,adiminRoute = true // pages that only admin can access
function AuthenticationCheck(props){
useEffect(()=>{
auth(accessToken).then(res => {
if (res.accessToken) {
setAccessToken(res.accessToken)
}
//when authentication failed
if (res.isAuth===false) {
if (option) {
//to sign in page
navigate('/signin')
}
//when authentication successed
} else {
//trying to get in admin page but user is not admin
if (adminRoute && res.role !== "Admin") {
navigate('/landingpage')
//trying to get in admin page and user is admin
} else if (adminRoute && res.role === "Admin") {
navigate('/admin')
} else {
//trying to get in login page but user is signed in already
if (option === false) {navigate('/landing')}
}
}
//passed above, go to SpecificComponent
});
},[])
return(
<SpecificComponent {...props} />
)
}
return AuthenticationCheck
}
当我运行此代码并尝试以管理员用户身份进入管理页面时,我可以进入管理页面但它陷入循环并一遍又一遍地重新呈现管理页面。
else if (adminRoute && res.role === "Admin") {
navigate('/admin')
}
所以我用另一个 react-router 方法 redirect 改变了导航,它工作得很好。 但是,我仍然不明白为什么导航不起作用但重定向起作用了?
这是重定向
export declare const redirect: RedirectFunction;
/**
* @private
* Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
*/
这是 useNavigate
export declare function useNavigate(): NavigateFunction;
/**
* Returns the context (if provided) for the child route at this level of the route
* hierarchy.
* @see https://reactrouter.com/docs/en/v6/hooks/use-outlet-context
*/
P.S 现在,我明白了它会进入管理页面,即使我像下面那样做了我的代码,但仍然不确定为什么 useNavigate 会陷入无限循环,这就是我想知道的
else if (adminRoute && res.role === "Admin") {
}
感谢阅读,您的帮助将不胜感激
【问题讨论】:
标签: reactjs react-router react-router-dom