简体   繁体   English

如何在Reactjs中使用session

[英]How to use session in Reactjs

I am new in Reactjs and I am working on "login" module, I integrated the login module successfully, and Now I want if the user enters the correct email and password then the email should be in session, And if the user is not logged in he can't see any further page, How can I do this?我是 Reactjs 的新手,我正在研究“登录”模块,我成功集成了登录模块,现在我想如果用户输入正确的 email 和密码,那么 email 应该在 session 中,如果用户未登录在他看不到任何进一步的页面,我该怎么做? Here is my current code这是我当前的代码

const data = {
  email: email,
  password: password
};
axios.post("https://xxxxxxxxxxx/Checklogin/", data).then(function (response) {
  if (response.data.msg == "wrong") {
    $("#errormsg4").show("slow").delay(5000).fadeOut();
  } else {
    //"response.data.email"should be in session
  }
});

To store the email in a session in React, as you specified, you can use the sessionStorage API. The sessionStorage API allows you to store key-value pairs in the user's browser.要将 email 存储在 React 中的 session 中,如您指定的那样,您可以使用sessionStorage sessionStorage API 允许您在用户的浏览器中存储键值对。 The data is stored in the session, which means it will only be available for the current tab and will be deleted when the user closes the tab.数据存储在 session 中,这意味着它仅适用于当前选项卡,并且在用户关闭选项卡时将被删除。

Here is an example of how you can use the sessionStorage API to store the email in a session:这是一个示例,说明如何使用sessionStorage API 将 email 存储在 session 中:

const data = {
  email: email,
  password: password
};
axios.post("https://xxxxxxxxxxx/Checklogin/", data).then(function (response) {
  if (response.data.msg == "wrong") {
    $("#errormsg4").show("slow").delay(5000).fadeOut();
  } else {
    // Store the email in the session
    sessionStorage.setItem("email", response.data.email);
  }
});

To check if the user is logged in, you can use the sessionStorage.getItem() method to retrieve the email from the session. If the getItem() method returns a non-null value, it means that the user is logged in and has an email stored in the session.查看用户是否登录,可以使用sessionStorage.getItem()方法从session中取出email。如果getItem()方法返回非空值,说明用户已经登录email 存储在 session 中。

Here is an example of how you can use the sessionStorage.getItem() method to check if the user is logged in:以下是如何使用sessionStorage.getItem()方法检查用户是否登录的示例:

const email = sessionStorage.getItem("email");
if (email) {
  // The user is logged in
} else {
  // The user is not logged in
}

I hope this helps!我希望这有帮助!

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM