英文:
useNavigate sometimes works, sometimes doesn't (after API call)
问题
我理解你的问题,你遇到了路由重定向的问题。这个问题可能是因为你的路由保护逻辑有些问题。以下是一些可能的解决方案:
-
确保Token正确存储:在登录成功后,你应该确保Token正确存储在
localStorage
中。你已经在localStorage.setItem("token", responseData.token)
这样做了,但要确保没有其他地方删除了这个Token。 -
检查ProtectedRoute逻辑:根据你提供的代码,问题可能出现在
ProtectedRoute
组件中。确保localStorage.getItem("token")
返回正确的认证状态。你可以在App组件中的isAuthenticated
变量上打印一些日志,以确保它的值是正确的。 -
确保Route正确匹配:确保你的路由配置是正确的。你已经将
<ProtectedRoute {...defaultProtectedRouteProps} outlet={<Home />} />
作为根路由的索引,这应该是正确的。但请确保没有其他地方有重复的路由匹配。 -
检查重定向触发时机:在
handleLogin
中,你设置了setTokenProvided(true)
,这应该触发路由重定向。确保这个部分按预期运行,也可以在这里添加一些日志来跟踪。
如果问题仍然存在,可能需要更多的代码和上下文来诊断问题。希望这些建议能帮助你找到问题所在。
英文:
I made a login page in TS React that sends an API request to authenticate the user.
The API call returns a token, after that the user should be redirected to "/"
(if successful).
Returning the token works 100% every time, but the redirect sometimes fails.
It seems like the page is being rerendered instead of redirecting. What am I doing wrong?
import { useNavigate } from "react-router-dom";
function Login() {
const [username, setUsername] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [tokenProvided, setTokenProvided] = React.useState<boolean>(false);
const navigate = useNavigate();
useEffect(() => {
document.title = "Login";
if(tokenProvided){
navigate('/')
}
}, [tokenProvided]);
const handleLogin = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
const loginData: loginData = { username, password };
const responseData = await getLoginToken(loginData);
localStorage.setItem("token", responseData.token);
const userAuthentificationToken = localStorage.getItem("token");
axios.defaults.headers.common["Authorization"] = `Bearer ${userAuthentificationToken}`;
setTokenProvided(true);
} catch (error) {
createErrorToast("Invalid username or password.");
}
return (
<Page backgroundColorActive={false} navbarActive={false}>
<LoginFormWrapper>
...bla...
<LoginForm onSubmit={handleLogin}>
...bla...
<LoginFormButton type="submit">Login</LoginFormButton>
</LoginForm>
</LoginFormWrapper>
</Page>
);
}
export default Login;
The behaviors is as follows:
- I enter the credentials on the page
- I hit submit
- I can see it working (takes a moment for the api call to return)
- The site rerenders
- I can see the token in local storage
Sometimes it will in fact redirect, but I don't know why or how or when.
Edit:
Here is my route protection:
App.tsx:
import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import ProtectedRoute, { ProtectedRouteProps } from "./helper/restrictedRoute";
const isAuthenticated = localStorage.getItem("token") !== null;
const defaultProtectedRouteProps: Omit<ProtectedRouteProps, "outlet"> = {
isAuthenticated: isAuthenticated,
authenticationPath: "/login",
};
function App() {
return (
<BrowserRouter>
<Routes>
{/* Unprotected routes: These routes can be accessed without being logged in */}
<Route path="/login" element={<Login />} />
{/* Protected routes: These routes can only be accessed while being logged in */}
<Route index element={<ProtectedRoute {...defaultProtectedRouteProps} outlet={<Home />} />} />
</Routes>
</BrowserRouter>
);
}
export default App;
RestrictedRoute.tsx:
import { Navigate } from "react-router-dom";
export type ProtectedRouteProps = {
isAuthenticated: boolean;
authenticationPath: string;
outlet: JSX.Element;
};
export default function ProtectedRoute({ isAuthenticated, authenticationPath, outlet }: ProtectedRouteProps) {
if (isAuthenticated) {
return outlet;
} else {
return <Navigate to={{ pathname: authenticationPath }} />;
}
}
The routing protection seems to be the problem, the else statement in RestrictedRoute.tsx gets executed, but I don't know how to fix that.
答案1
得分: 1
以下是代码的中文翻译:
- 当处理/挂载“App”文件/组件时,仅会检查一次localStorage。 “isAuthenticated”在应用程序之外计算一次。
const isAuthenticated = localStorage.getItem("token") !== null;
- 应将localStorage检查移到“ProtectedRoute”中,并在组件渲染时进行检查。 “ProtectedRoute”还应呈现“Outlet”组件,以便保护嵌套路由将其内容呈现为。
import { Navigate, Outlet } from "react-router-dom";
export type ProtectedRouteProps = {
authenticationPath: string;
};
export default function ProtectedRoute({ authenticationPath }: ProtectedRouteProps) {
const isAuthenticated = localStorage.getItem("token") !== null;
return isAuthenticated
? <Outlet />
: <Navigate to={authenticationPath} replace />;
}
- 路由如下编写:
import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import ProtectedRoute, { ProtectedRouteProps } from "./helper/restrictedRoute";
const defaultProtectedRouteProps: ProtectedRouteProps = {
authenticationPath: "/login",
};
function App() {
return (
<BrowserRouter>
<Routes>
{/* 未受保护的路由:未登录用户可以访问这些路由 */}
<Route path="/login" element={<Login />} />
{/* 受保护的路由:只有登录用户才能访问这些路由 */}
<Route element={<ProtectedRoute {...defaultProtectedRouteProps} />}>
<Route path="/" element={<Home />} />
</Route>
</Routes>
</BrowserRouter>
);
}
export default App;
英文:
The localStorage is checked only once when the App
file/component is processed/mounted. isAuthenticated
is computed once outside anything in the app.
const isAuthenticated = localStorage.getItem("token") !== null;
The localStorage check should be moved into the ProtectedRoute
and checked when the component renders. ProtectedRoute
should also render the Outlet
component for protected nested routes to render their content into.
import { Navigate, Outlet } from "react-router-dom";
export type ProtectedRouteProps = {
authenticationPath: string;
};
export default function ProtectedRoute({ authenticationPath }: ProtectedRouteProps) {
const isAuthenticated = localStorage.getItem("token") !== null;
return isAuthenticated
? <Outlet />
: <Navigate to={authenticationPath} replace />;
}
The routes written as follows:
import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import ProtectedRoute, { ProtectedRouteProps } from "./helper/restrictedRoute";
const defaultProtectedRouteProp: ProtectedRouteProps = {
authenticationPath: "/login",
};
function App() {
return (
<BrowserRouter>
<Routes>
{/* Unprotected routes: These routes can be accessed without being logged in */}
<Route path="/login" element={<Login />} />
{/* Protected routes: These routes can only be accessed while being logged in */}
<Route element={<ProtectedRoute {...defaultProtectedRouteProps} />}>
<Route path="/" element={<Home />} />
</Route>
</Routes>
</BrowserRouter>
);
}
export default App;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论