我正在try 实现到我的应用程序的私有路由,虽然它在经过身份验证时正确地到达了私有路由,但它会将其重定向到登录页面,而不是子页面.我try 了堆栈溢出的所有解决方案,但似乎都不起作用.这很奇怪,因为它到达了正确的路径(每当我到达私有路由时,我都会打印到控制台),但它无法正确地重定向页面.
PrivateRouting专用路由
import { useState, useEffect } from 'react';
import { useRef } from 'react';
import { Outlet, Navigate, useLocation } from 'react-router-dom';
import Axios from "axios";
import Cookies from "universal-cookie";
export default function ProtectedRoute({ children }) {
const [isAuthenticated, setIsAuthenticated] = useState();
// add loading state, initially true for initial render
const [isLoading, setIsLoading] = useState(true);
const checkAuth = async () => {
const cookie = new Cookies();
setIsLoading(true); // <-- set true when starting auth check
try {
if (cookie.get("stytch_session") == null) {
console.log("no cookies!")
setIsAuthenticated(false);
} else {
Axios.post(
"http://localhost:5001/test",
{},
{ headers: { sessiontoken: cookie.get("stytch_session") } }
)
.then((response) => {
console.log("reaching private route!")
setIsAuthenticated(true);
})
.catch((err) => {
console.log(err)
setIsAuthenticated(false);
});
}
} finally {
setIsLoading(false); // <-- clear loading state when completed
}
};
useEffect(() => {
checkAuth();
}, []);
if (isLoading) {
return <div className="">Loading...</div>;
}
return isAuthenticated ? children : <Navigate to={"/login"} />;
}
下面是在app.js中调用的代码片段
<Route
path="/scroll"
element={(
<ProtectedRoute>
<Scroll />
</ProtectedRoute>
}
/>