英文:
how to update (when login put token and logout reset) global variable in react for use it on all conponents
问题
我尝试在React中创建一个全局变量。我成功地创建了全局变量并在用户登录时更新它,但当我刷新页面或转到另一个页面时,该变量会被清除。
例如,当我通过表单连接用户,如果数据有效,我会将令牌放入变量中,如下所示:
import React, { useEffect, useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import globalToken from '../GlobalVariable';
const Login: React.FC = () => {
// ... 其他代码 ...
useEffect(() => {
// ... 其他代码 ...
fetch("https://bilemo.thomas-dasilva.fr/BileMo/login_check", requestOptions)
.then((response) => response.text())
.then((result: any) => {
if (result !== '{"code":401,"message":"Invalid credentials."}') {
let token: any = JSON.parse(result);
globalToken.test = token.token; // 在这里设置全局变量
setLogin(true);
return navigate("/home");
}
})
.catch((error) => console.log("error", error));
});
// ... 其他代码 ...
};
export default Login;
当用户登录后,我通过上面的代码设置了全局变量globalToken.test
。但当我刷新页面或转到其他页面时,该变量被清除。
为了解决这个问题,你可以使用浏览器的本地存储功能来保存全局变量,以便在页面刷新或导航到其他页面时保留数据。例如,你可以使用localStorage
:
// 在登录成功后保存全局变量到本地存储
localStorage.setItem('globalToken', JSON.stringify(globalToken));
// 在应用启动时从本地存储中获取全局变量
const storedToken = localStorage.getItem('globalToken');
const globalToken = storedToken ? JSON.parse(storedToken) : { test: "" };
这样,全局变量将在页面刷新或导航到其他页面时保持不变。然后,你可以使用globalToken.test
来检查用户是否已连接。不过,请注意,本地存储中的数据可能会受到浏览器隐私设置的限制,因此需要谨慎使用。
英文:
I try to make a global variable in react. I succeeded to have global variable and update it when user is login but when I refresh page or go on an another page the variable is clear.
for example I connect with form the user if data is good I put the token in variable like this :
import React, { useEffect, useState } from "react";
import { Navigate, redirect, useNavigate } from "react-router-dom";
import { json } from "stream/consumers";
import Fetch from "../conponents/Fetch";
import globalToken from '../GlobalVariable'
const Login: React.FC = () => {
var [user, setUser] = useState<string>("");
var [pass, setPass] = useState<string>("");
var [login, setLogin] = useState<boolean>(false);
const navigate = useNavigate();
useEffect(() => {
//async function dataFetch(user: string, pass: string) {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
var raw =
'{\n "username": "' + user + '",\n "password": "' + pass + '"\n}';
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
};
fetch("https://bilemo.thomas-dasilva.fr/BileMo/login_check", requestOptions)
.then((response) => response.text())
.then((result: any) => {
if (result !== '{"code":401,"message":"Invalid credentials."}') {
let token: any = JSON.parse(result);
//process.env.REACT_APP_TOKEN = token.token;
//console.log(process.env.REACT_APP_TOKEN)
globalToken.test = token.token
setLogin(true);
return navigate("/home");
}
})
.catch((error) => console.log("error", error));
//}
});
return (
<>
<main>
<section>
<h1>Login</h1>
<form
method="POST"
onSubmit={(e) => {
e.preventDefault();
var inputUser = document.getElementById(
"username"
) as HTMLInputElement;
var inputPassword = document.getElementById(
"password"
) as HTMLInputElement;
setUser(inputUser.value);
setPass(inputPassword.value);
//<Fetch username="test" password="test" />;
}}
>
<div>
<label htmlFor="username">Username</label>
<input
type="text"
name="username"
id="username"
data-testid="username"
/>
</div>
<div>
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
id="password"
data-testid="password"
/>
</div>
<button type="submit" data-testid="btnLogin">
Go login
</button>
</form>
</section>
</main>
</>
);
};
export default Login;
when the user I redirect and I console.log(globalToken.test) I have the token in but when I refresh or change page the variable is clear and return the initial value.
I setup variable like this :
var globalToken = {test: ""}
export default globalToken
I put this in a file and I import it on other conponent
I have try with window but didn't work and with global
I would like to use this variable to check if the user is connect on no, for example if var not empty is :
if (globalToken.test.length > 1) {
}
but variable not register the token when I refresh page.
It's possible with react to do this ?
答案1
得分: 1
你需要使用sessionStorage
或localStorage
来在重新加载页面时保留数据,这些功能可通过window
对象获得。这个优雅的钩子几乎完全回答了你的问题。
英文:
You need to use either a sessionStorage
or localStorage
to persist data across reloads, which is available thru the window
object. This elegant hook pretty much answers your question.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论