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

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 below
  if (user) {
    return <div>{user.name} is loggged in</div>;
  }

  // if there's no user, show the login form
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="username">Username: </label>
      <input
        type="text"
        value={username}
        placeholder="enter a username"
        onChange={({ target }) => setUsername(target.value)}
      />
      <div>
        <label htmlFor="password">password: </label>
        <input
          type="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 server
  const response = await axios.post(
    "http://blogservice.herokuapp.com/api/login",
    user
  );
  // set the state of the user
  setUser(response.data)
  // store the user in localStorage
  localStorage.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页面保留

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值