首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ReactJs中的用户登录问题

ReactJs中的用户登录问题
EN

Stack Overflow用户
提问于 2020-08-27 14:32:17
回答 1查看 32关注 0票数 0

我在一个项目中工作,它的主页包含一个登录表单,要求用户插入电子邮件和密码,然后通过-if认证-用户导航到个人资料页面。下面是我在React中实现私有路由的代码部分:

代码语言:javascript
运行
复制
import { Route, Redirect } from 'react-router-dom';

export const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
        localStorage.getItem('user')
            ? <Component {...props} />
            : <Redirect to={{ pathname: `${baseURL}/`, state: { from: props.location } }} />
    )} />
)

问题是,如果我把主页的链接,即使我已经登录,它导航到主页,并要求我再次输入电子邮件和密码。我想做一些事情,重定向到配置文件页面,如果他插入了主页的链接,而他的令牌仍然有效,没有过期。它是如何做到的?有什么帮助吗?

谢谢你的提醒。

EN

回答 1

Stack Overflow用户

发布于 2020-08-27 15:44:56

你还需要在你的主页上安装一个localStorage检查器。

代码语言:javascript
运行
复制
useEffect(() => {
   
      /*back to profile if the user attempt to go to home page even the user was currently logged-in*/
     
     const isUserLogged = localStorage.getItem('user');
     if (isUserLogged) {
          return props.history.push(`/profile`);
     }
 }, []);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63610382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档