如何检查用户是否登录以及如何保存他们的信息?(反应) [英] How to check if a user is logged in and how to save their information? (React)

查看:62
本文介绍了如何检查用户是否登录以及如何保存他们的信息?(反应)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎让登录页面与后端通信以登录用户.现在我想获取他们的数据并将其存储以供我所有其他组件使用,以便知道有

So pretty much I made a login page communicates with a backend to login a user. Now I want to take their data and store it for all my other components to know that there is

  1. 一个用户登录
  2. 有权访问用户的信息

根据过去的 StackOverflow 答案,我认为最好的方法是使用 JWT 和 LocalStorage.但是我遇到的所有答案似乎都使​​用 Redux.我的应用程序根本没有使用 Redux,也不知道如何使用它,所以我想知道是否有没有 Redux 的方法.

I figured based on past StackOverflow answers, that the best way to do this is using JWT and LocalStorage. But all the answer's I've encountered seem to use Redux. I'm not using Redux at all for my application, and have no clue how to use it, so I was wondering if there's a way to do it without redux.

推荐答案

你不需要 Redux.您只需要将 JWT 存储在 localStorage 中.为此,当您收到来自 API 的登录成功响应时,只需使用 localStorage.setItem('token', data.token) 即可.就这么简单.您可以阅读这篇文章了解更多详情.它适用于 React Redux 应用程序,但不需要 Redux.

You don't need Redux. You just have to store the JWT in localStorage. To do that, just use localStorage.setItem('token', data.token) when you receive the login success response from the API. It's that simple. You can read this article for more details. It's for React Redux applications but doesn't need Redux.

那么,假设你使用的是 react-router,你需要两个辅助函数.第一个将在您的受保护路由上运行,如下所示:

Then, assuming you are using react-router, you need two helper functions. The first will go on your protected routes and would look like this:

const requireAuth = (...) => {
  if(!localStorage.getItem('token')) {
    // go to login route
  }
  // stay on this route since the user is authenticated
}

第二个在未受保护的路由上运行,如下所示:

The second goes on your unprotected routes and looks like this:

const verifyAuth = (...) => {
  if(localStorage.getItem('token')) {
    // go to your dashboard or home route
  }
  // stay on this route since the user is not authenticated
}

请记住,您必须根据服务器到期时间刷新令牌.一个好的方法是创建一个对服务器的调用,询问令牌是否仍然有效.

Keep in mind that you have to refresh the token according to the server expiration time. A good approach would be to create a call to the server asking if the token is still valid.

这篇关于如何检查用户是否登录以及如何保存他们的信息?(反应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆