简体   繁体   English

ReactJS:本地存储需要时间来存储令牌,并且登录页面无法首次重定向到仪表板路由

[英]ReactJS: Local Storage taking time to store token, and login page is unable to redirect first time to dashboard route

I am following this procedure:我正在按照这个程序:

- Hitting to Login API
- Getting Success response containing token
- Setting the token to local storage
- Trying to redirect to protected routes
- Protected component check the token from local storage
- For the first time, it is not getting token from local storage as local storage take some time to store token on local storage
- As the token not set yet to local storage, it assumes the use as not authenticated, and then is now redirecting to the login page for the first time.

Moreover, if I keep my token to the state, and then try to check the authentication taking the token from state, then If I logout from one tab or window, then rest of tabs are not logged out automatically.此外,如果我将令牌保存到 state,然后尝试检查从 state 获取令牌的身份验证,那么如果我从一个选项卡或 window 注销,则 rest 个选项卡不会自动注销。 And need to logout from all tabs manually.并且需要手动从所有选项卡注销。

ProtectedRouter.jsx ProtectedRouter.jsx

import { Navigate, Route } from "react-router-dom";
import useAuth from "../hooks/useAuth";

const ProtectedRouter = ({ component }) => {
    const auth = JSON.parse(localStorage.getItem("token")) ?? false; 

    if(auth) {
        return component;
    } else {
        return <Navigate replace to="/login"/>
    }
};

export default ProtectedRouter;

Router.jsx路由器.jsx

<Route element={<Layout/>}>
    <Route path="/" element={<ProtectedRouter component={<Dashboard/>}/>}/>
</Route>

Login.jsx登录.jsx

const login = ({email, password}) => {
    axios.post(`http://localhost:7000/api/users/login`, { email, password }).then(response => {
        localStorage.setItem("loggedInUser", JSON.stringify(loggedInUser));
        localStorage.setItem("token", JSON.stringify(token));
    }).catch(err => {
        console.error(err.message().toString());
    });
};

It has been 3 months since the question was asked, but maybe this can help someone else.自提出问题以来已经 3 个月了,但这也许可以帮助其他人。 I find using navigate('/route-to', { replace: true });我发现使用navigate('/route-to', { replace: true }); very useful as it refreshes the page making it possible for the token to be available on local storage.非常有用,因为它刷新页面,使令牌可以在本地存储上可用。 I can't see where you are redirecting after a successful login.登录成功后,我看不到你重定向到哪里。 You should redirect like this navigate('/', { replace: true });你应该像这样重定向navigate('/', { replace: true }); Also, where are you getting the token and loggedInUser from?另外,您从哪里获取令牌和 loggedInUser? After a successful login, the API is returning token, so you should get loggedInUser and token from the response.成功登录后,API 返回令牌,因此您应该从响应中获取 loggedInUser 和令牌。

Here is what you can do.这是您可以做的。

const login = ({email, password, navigate}) => {
  axios.post(`http://localhost:7000/api/users/login`, { email, password }).then(response => {
      localStorage.setItem("loggedInUser", JSON.stringify(response.data.loggedInUser));
      localStorage.setItem("token", JSON.stringify(response.data.token));
      navigate('/', { replace: true });
  }).catch(err => {
      console.error(err.message().toString());
  });
};

Dont forget to pass navigate ( useNavigate ) when using login() .使用login()时不要忘记传递 navigate ( useNavigate )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 ReactJS 将登录页面重定向到仪表板? - How to redirect login page to dashboard using ReactJS? 将令牌存储在 cookie 中或 reactjs 中的本地存储中 - store token in cookie or local storage in reactjs ReactJS + Redux:如果令牌在本地存储中,如何直接导航到页面(跳过登录)? - ReactJS + Redux: How to directly navigate to a page (skip login) if token is in local storage? 如果用户第一次访问jQuery中的页面,如何确定本地存储 - How to determine local storage if the user is accessing the page for the first time in jQuery 如何在ReactJS + REDUX中输入索引路径之前重定向到登录页面 - How To Redirect to Login Page Before Entering Index Route in ReactJS + REDUX 首次访问时,弹出一个div询问用户名,然后将其和日期存储在本地存储中 - On first time visit- popup a div asking user name, then store it and the date on local storage 首次登录angular js后,如何自动将页面从“ /”路由重定向到主“ / dashboard”路由? - How to redirect a page from '/' route to main '/dashboard' route automatically after first sign in angular js? 在reactjs中登录后无法重定向 - unable to redirect after login in reactjs 为什么第一次登录时注册成功后显示空白屏幕,重新加载页面后显示仪表板屏幕 - Why after register successfully when first time login blank screen showing, after reload the page then showing the dashboard screen angularJS 无法从登录页面重定向到散列路由 - angularJS unable to redirect to hashed route from login page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM