我正在尝试建立一条受保护的路由,其中要考虑的参数为useAuth()
。
useAuth,获取令牌和Userid,并向后端发出get请求。
问题是,当我导航到/ admin时,它会显示useAuth为false,但是当它进入首页时,useAuth往往为true。
const useAuth = () => {
const [isAuthenticated, setAuth] = useState(false);
const { state : {user, token}} = useContext(userContext);
console.log(user, token)
const headers = {
"x-access-token": token,
"Content-Type": "application/json"
}
useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
async function onLoad() {
if (user && token) {
try {
await Axios.get(`${process.env.REACT_APP_API || "http://localhost:5000/"}api/user/${user._id}`, {headers})
if (!signal.aborted) {
setAuth(true);
}
}
catch (error) {
if (!signal.aborted) {
setAuth(false)
}
}
}
else{
if (!signal.aborted) {
setAuth(false)
}
}
}
onLoad()
return () => {
abortController.abort();
};
},[user, token, headers]);
return isAuthenticated;
};
也是路线的HOC组件
export const AuthenticatedRoute = ({ children, ...rest }) => {
const { pathname, search } = useLocation();
const isAuthenticated = useAuth();
return (
<Route {...rest}>
{ isAuthenticated ? (
children
) : (
<Redirect to={
`/login?redirect=${pathname}${search}`
} />
)}
</Route>
);
};
这里是issue
的小复制品