关于reactjs:在React中管理用户会话的最佳方法是什么?

What is the best way to manage a user's session in React?

我对如何在React中管理用户会话存有疑问,例如在MVC .NET中,您仅使用Session对象(例如Session["test"] ="";)来执行此操作,但显然React无法做到这一点。

我正在阅读有关使用组件状态的信息,我想将状态设置为主要组件,然后使用props将该状态传递给其他组件。我也看到有人建议使用浏览器的localStorage或cookie,但是我不知道这是否是个好主意或做法。

localStorage或cookie相比,在React中是否有更好的方法来管理会话变量?


我将避免使用组件状态,因为这可能难以管理并且容易出现难以解决的问题。

您应该使用cookieslocalStorage来保留用户的会话数据。您也可以将闭包用作cookielocalStorage数据的package。

这是UserProfile闭包的简单示例,其中将保留用户名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var UserProfile = (function() {
  var full_name ="";

  var getName = function() {
    return full_name;    // Or pull this from cookie/localStorage
  };

  var setName = function(name) {
    full_name = name;    
    // Also set this in cookie/localStorage
  };

  return {
    getName: getName,
    setName: setName
  }

})();

export default UserProfile;

用户登录时,可以用用户名,电子邮件地址等填充此对象。

1
2
3
import UserProfile from './UserProfile';

UserProfile.setName("Some Guy");

然后,您可以在需要时从应用程序中的任何组件获取此数据。

1
2
3
import UserProfile from './UserProfile';

UserProfile.getName();

使用闭包会将数据保留在全局名称空间之外,并使您可以从应用程序中的任何位置轻松访问它们。


仅举几例,我们可以使用redux-react-session,它具有良好的会话管理API,例如initSessionServicerefreshFromLocalStoragecheckAuth等。它还提供了一些高级功能,例如Immutable JS

或者,我们可以利用react-web-session来提供callbacktimeout之类的选项。


这不是管理会话的最佳方法,您可以使用Web令牌对要保存的数据进行加密,可以使用多种可用的服务,其中流行的是带有Web令牌的JSON Web令牌(JWT)如果客户端没有任何操作,则可以在一段时间后注销。创建令牌后,可以将其存储在本地存储中以方便访问。

1
2
3
4
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
    res.json({
      token
  });

此处的

user对象是您要保留在会话中的用户数据

1
localStorage.setItem('session',JSON.stringify(token));


有一个名为react-client-session的React模块,它使存储客户端会话数据非常容易。 git repo在这里。

这以与我的其他答案中的闭包方法类似的方式实现,但是它也支持使用3种不同的持久性存储的持久性。默认存储为内存(非持久性)。

  • 曲奇饼
  • 本地存储
  • sessionStorage
  • 安装后,只需设置所需的存储类型即可在其中安装根组件...

    1
    2
    3
    import ReactSession from 'react-client-session';

    ReactSession.setStoreType("localStorage");

    ...并从应用程序中的任何位置设置/获取键值对:

    1
    2
    3
    4
    import ReactSession from 'react-client-session';

    ReactSession.set("username","Bob");
    ReactSession.get("username");  // Returns"Bob"