我对如何在 React 中管理用户会话有疑问,例如在 MVC .NET 中,您只能使用 Session 对象(例如Session["test"] = "";
),但显然 React 无法做到这一点。
我正在阅读有关使用组件状态的内容,我认为在主要组件处设置状态并使用 props 将此状态传递给其他组件。我还看到有人推荐使用浏览器localStorage
或饼干,但我不知道这是否是一个好主意或做法。
在 React 中是否有更好的方法来管理会话变量localStorage
或者饼干?
我会避免使用组件状态,因为这可能难以管理并且容易出现难以解决的问题。
你应该使用cookies
or localStorage
用于保存用户的会话数据。您还可以使用闭包作为您的包装物cookie
or localStorage
data.
这是一个简单的例子UserProfile
将保存用户名的闭包。
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;
当用户登录时,您可以使用用户名、电子邮件地址等填充此对象。
import UserProfile from './UserProfile';
UserProfile.setName("Some Guy");
然后,您可以在需要时从应用程序中的任何组件获取此数据。
import UserProfile from './UserProfile';
UserProfile.getName();
使用闭包会将数据保留在全局命名空间之外,并使其可以从应用程序中的任何位置轻松访问。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)