react页面保留

If you run a quick Google search for persisting a logged-in user in React (or keeping a user logged in in React), you don't get a lot of straightforward results. There aren't really any easy to follow examples on how to achieve this. So I decided I had to write that simple guide.

如果您运行Google快速搜索以将已登录的用户保留在React中(或使用户保持在React中的登录状态),则不会得到很多直接的结果。 关于如何实现此目标,实际上并没有容易遵循的示例。 因此,我决定必须编写该简单指南。

You may have done a search on this and saw the word localStorage being thrown around. Yes, we'll be using localStorage but I'm going to show you exactly how it's done.

您可能对此进行了搜索,并看到单词localStorage被抛出。 是的,我们将使用localStorage,但我将向您确切演示它是如何完成的。

关于localStorage的一些说明。 (Some notes on localStorage.)

  1. localStorage is the browser's database. The data is stored inside your browser in your computer's memory.

    localStorage是浏览器的数据库。 数据存储在浏览器内部的计算机内存中。

  2. localStorage is specific to an origin. In other words, the localStorage for one website cannot be accessed by another.

    localStorage特定于来源。 换句话说,一个网站的localStorage无法被另一个网站访问。

最初设定 (Initial setup)

Let's get started. I've deployed a simple express server to Heroku for use in testing this application.

让我们开始吧。 我已经在Heroku上部署了一个简单的快速服务器,用于测试该应用程序。

  1. Create a new React application and head into the <App /> component.

    创建一个新的React应用程序并进入<App />组件。

  2. Install axios using npm install axios and import it inside <App />

    使用npm install axios并将其导入<App />

  3. Next, create a simple login form that accepts a username and password. 接下来,创建一个接受用户名和密码的简单登录表单。
import React, { useState } from "react";
import axios from "axios";const App = () => {const [username, setUsername] = useState("");const [password, setPassword] = useState("");const [user, setUser] = useState()const handleSubmit = async e => {};// if there's a user show the message belowif (user) {return <div>{user.name} is loggged in</div>;}// if there's no user, show the login formreturn (<form onSubmit={handleSubmit}><label htmlFor="username">Username: </label><inputtype="text"value={username}placeholder="enter a username"onChange={({ target }) => setUsername(target.value)}/><div><label htmlFor="password">password: </label><inputtype="password"value={password}placeholder="enter a password"onChange={({ target }) => setPassword(target.value)}/></div><button type="submit">Login</button></form>);
};export default App;

As you can see, we've defined an asynchronous handleSubmit function to process the login request. We've also defined a conditional that displays a user.name is logged in message if we have a user, and the login form if we do not have a user.

如您所见,我们定义了一个异步handleSubmit函数来处理登录请求。 我们还定义了一个显示用户的条件如果有用户,则显示登录消息;如果没有用户,则显示登录表单。

Next, let's complete the function. This function will work in the following steps:

接下来,让我们完成功能。 此功能将按以下步骤工作:

  1. Send the login details to the server.将登录详细信息发送到服务器。
  2. If the request is successful (async-await), store the user information in                 localStorage and set the State of the User.如果请求成功(async-await),则将用户信息存储在localStorage中并设置“用户状态”。

处理登录事件 (Handle the login event)

Let's define the handleSubmit event handler.

让我们定义handleSubmit事件处理程序。

const handleSubmit = async e => {e.preventDefault();const user = { username, password };// send the username and password to the serverconst response = await axios.post("http://blogservice.herokuapp.com/api/login",user);// set the state of the usersetUser(response.data)// store the user in localStoragelocalStorage.setItem('user', response.data)console.log(response.data)
};

Note: Use a tryCatch block to handle errors in async functions.

注意:使用tryCatch块来处理异步函数中的错误。

Now that our function is done, you can run npm start to test out your app. Login with the username: user2, password: password.

现在我们的功能已经完成,您可以运行npm start来测试您的应用程序。 使用用户名 :user2登录, 密码 :password。

You should receive the following as a response. The userId, token and username

您应该收到以下答复。 userId令牌用户名

检查用户以前是否已登录 (Check if a user has previously logged in)

Next, we want a way to check if there's a user logged in each time the App loads. For that, we use the useEffect hook.

接下来,我们想要一种方法来检查每次加载应用程序时是否都有用户登录。 为此,我们使用useEffect挂钩。

useEffect(() => {const loggedInUser = localStorage.getItem("user");if (loggedInUser) {const foundUser = JSON.parse(loggedInUser);setUser(foundUser);}}, []);

Remember to use an empty dependency array in your useEffect hook so that it checks if there's a logged in user the first time the app loads.

请记住在useEffect挂钩中使用一个空的依赖项数组,以便它在应用程序首次加载时检查是否有登录用户。

Now our app should work perfectly. We get the page below after a user has logged in for the first time and their details are stored. If you refresh the page, you'll see that our user stays logged in and the logged in page continues to show.

现在我们的应用程序应该可以完美运行了。 用户首次登录并存储其详细信息后,我们将显示以下页面。 如果刷新页面,您会看到我们的用户保持登录状态,并且登录页面继续显示。

As a bonus tip, here's how to implement logout.

作为一个额外的提示,这是实现注销的方法。

实施注销功能 (Implementing Logout functionality)

For logging out, we simply empty the user state and remove the user from localStorage.

为了注销,我们只需清空用户状态并将用户从localStorage中删除。

Let's implement that.

让我们实现它。

First, we create a logout button

首先,我们创建一个注销按钮

<button onClick={handleLogout}>logout</button>

Then, we create the logout function.

然后,我们创建注销功能。

const handleLogout = () => {setUser({});setUsername("");setPassword("");localStorage.clear();};

And that's it, we're done.

就是这样,我们完成了。

Here's a link to the full gist on GitHub. You can follow me there for more updates.

这是GitHub上完整要点的链接。 您可以在这里关注我以获取更多更新。

翻译自: https://www.freecodecamp.org/news/how-to-persist-a-logged-in-user-in-react/

react页面保留

react页面保留_如何在React中保留已登录的用户相关推荐

  1. react本地储存_如何在React项目中利用本地存储

    react本地储存 以及为什么要这么做. 本地存储是现代Web浏览器固有的Web API. 它允许网站/应用程序在浏览器中存储数据(简单和有限),从而使数据在以后的浏览器会话中可用. 在开始学习本教程 ...

  2. webbrowser控件 有数据 但页面空白_如何在Excel中实现可以切换不同数据系列的滚珠图?...

    ▲更多精彩内容,请点击上方Excel小铲子▲ 操作系统版本 Windows 10 64位 Excel版本 Microsoft Excel 2016 64位 案例文档下载 链接:https://pan. ...

  3. react 错误边界_如何在React 16中使用错误边界

    react 错误边界 Have you seen these in your console? 您是否在控制台中看到了这些? Cannot read property 'getHostNode'of ...

  4. react入门代码_如何在React中构建温度控制应用程序-包括提示和入门代码

    react入门代码 我们正在建立的 (What we're building) In this beginner React project, we're going to learn how to ...

  5. java 保留字符串,如何在Java中保留字符串而不使用反转功能

    有以下几种在Java中反转字符串的方法: 使用for循环 使用While循环 使用静态方法 使用For循环 使用for循环在Java中反转字符串的示例 在下面的示例中, 我们使用了for循环来反转字符 ...

  6. 在excel日期比对大小_如何在Excel中防止分组日期

    在excel日期比对大小 As a teenager, group dates can be fun. If you have strict parents, that might be the on ...

  7. figma设计_如何在Figma中构建设计入门套件(第1部分)

    figma设计 Figma教程 (Figma Tutorial) Do you like staring at a blank canvas every time you start a new pr ...

  8. java位宽_在系统verilog中保留枚举中的位宽

    我如何在Enum中保留位宽? 例如,在以下代码中: - typedef enum bit[2:0] { b1=2'b10, b2=3'b100 }b; {// regular stuff module ...

  9. 表格在整个html居中显示,html 表格字符居中显示_如何在HTML中居中显示表格?

    html 表格字符居中显示_如何在HTML中居中显示表格? html 表格字符居中显示_如何在HTML中居中显示表格? html 表格字符居中显示 HTML table provides the ab ...

最新文章

  1. Android 关于::app:clean :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE,引用jar冲突问题...
  2. 全方位复盘GNN,12位大神寄望2021年大爆发
  3. 了解DELL的raid卡电池相关信息
  4. SQL语句大全,所有的SQL都在这里
  5. 九大技巧教你快速提升移动应用登陆转化率
  6. outlook搜索不到历史邮件内容
  7. 机器学习中的不平衡分类方法(part3)--不平衡分类学习策略
  8. DataTime转Varchar
  9. select a method for export 选项
  10. ProxyPass与ProxyPassReverse及ProxyPassMatch的概述
  11. java表单单击路径_Form表单中的action路径问题,form表单action路径《jsp---Servlet路劲问题》这个和上一个《jsp---Servlet》文章有关...
  12. 【转】Linux里如何查找文件内容
  13. 【现代卫星导航系统】之北斗卫星导航系统
  14. 删除或复制文件提示:文件名无效或太长/目标路径太长/找不到该项目
  15. python三阶魔方_三阶魔方7步还原法详解 简单
  16. 决定RDD分区数因素、关联
  17. 什么是LOST.DIR?
  18. RocketMQ的长轮询消费方式
  19. SPSS Modeler 建模前准备—数据平衡与特征选择(指南 第十一章)
  20. RouterOS(ros)自动更新国内外IP以及端口扫描IP

热门文章

  1. jquery-表格的增删编辑演练-有一个小bug的
  2. jquery-节点操作
  3. SQL Server全局禁用及打开指定的跟踪标记
  4. Windows Azure 部署 Windows 8 虚拟机
  5. Buffer与Cache
  6. koa-router 源码浅析
  7. 通用单向链表设计(一)——接口的设计
  8. 2013年6月13日星期四
  9. 泛型那点儿事儿 泛型概述 简单样例代码
  10. 前端面试:你应该了解的JS算法相关的知识