在 React 中管理用户会话的最佳方式是什么? [英] What is the best way to manage a user's session in React?
问题描述
我对如何在 React 中管理用户会话存有疑问,例如在 MVC .NET 中,您只能使用 Session 对象来执行此操作(例如 Session["test"] = "";
),但显然 React 做不到这一点.
I have a doubt about how to manage a user's session in React, for example in MVC .NET you only just do this using the Session object (e.g. Session["test"] = "";
), but obviously React can not do this.
我正在阅读有关使用组件状态的文章,我想这会在主组件上设置状态,并使用 props 将此状态传递给其他组件.我也看到有人推荐使用浏览器的 localStorage
或 cookie,但我不知道这是否是一个好主意或实践.
I was reading about using the component state, I suppose that sets the state at the principal component and passes this state to other components using props. Also I saw people recommending the use the browser's localStorage
or cookies, but I don't know if this if a good idea or practice.
有没有比 localStorage
或 cookie 更好的方法来管理 React 中的会话变量?
Is there a better way to manage sessions variables in React than localStorage
or cookies?
推荐答案
我会避免使用组件状态,因为这可能难以管理并且容易出现难以解决的问题.
I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.
您应该使用 cookies
或 localStorage
来保存用户的会话数据.您还可以使用闭包作为 cookie
或 localStorage
数据的包装器.
You should use either cookies
or localStorage
for persisting a user's session data. You can also use a closure as a wrapper around your cookie
or localStorage
data.
这是一个 UserProfile
闭包的简单示例,该闭包将保存用户名.
Here is a simple example of a UserProfile
closure that will hold the user's name.
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;
当用户登录时,您可以使用用户名、电子邮件地址等填充此对象.
When a user logs in, you can populate this object with user name, email address etc.
import UserProfile from './UserProfile';
UserProfile.setName("Some Guy");
然后,您可以在需要时从应用中的任何组件获取这些数据.
Then you can get this data from any component in your app when needed.
import UserProfile from './UserProfile';
UserProfile.getName();
使用闭包会将数据保留在全局命名空间之外,并使其可以从应用中的任何位置轻松访问.
Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.
这篇关于在 React 中管理用户会话的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!