我正在开发React - Express - Mongo中的应用程序,我如何在浏览器关闭或页面刷新后保持用户登录?
在LocalStorage或Cookies中存储JWT令牌。这是最简单的方法。
查看这里- https://www.freecodecamp.org/news/how-to-persist-a-logged-in-user-in-react/
一个简单的例子,让你理解如何使用localStorage,sessionStorage .
https://www.geeksforgeeks.org/difference-between-local-storage-session-storage-and-cookies/
// After hitting login button
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)
};
- 在登录API调用中创建jwt令牌,并在登录时返回它作为响应
- 将它们存储在cookie存储或本地存储(我建议使用饼干)
- 检查登录页面或注册页面上是否存在令牌页面(如果存在),将页面重定向到登录
const [isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(()=>{
const localstorageGetInformation=localStorage.getItem('isLoggedIn')
if(localstorageGetInformation=='1'){
setIsLoggedIn(true)
}
},[])
const loginHandler = (email, password) => {
localStorage.setItem("isLoggedIn",'1')
setIsLoggedIn(true);
};
假设您有这样的内容:
const MyComponent = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
// your code
}
你可以这样做:
const initialLoggedInState = localStorage.getItem('isLoggedIn') ?? false;
const MyComponent = () => {
const [isLoggedIn, setIsLoggedIn] = useState(initialLoggedInState === 'true');
useEffect(() => {
localStorage.setItem('isLoggedIn', isLoggedIn);
}, [isLoggedIn]);
// your code
}