[英]Cookies not being set immediately in react
我正在使用 djangorestauth 作为后端,它返回的令牌没有立即保存在通用 cookies 的 cookies 中。 我有这个句柄登录:
const handleLogin = (e) => {
e.preventDefault();
setIsClicked(true);
const csrftoken = getCookie("csrf");
const url = "http://localhost:8000/rest-auth/login/";
const cookies = new Cookies();
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({
username: username,
password: password,
}),
})
.then((response) => response.json())
.then((key) => setToken(key.key));
cookies.set("token", token);
};
和一个 useEffect() 来测试
useEffect(() => {
if (isClicked) {
const cookies = new Cookies();
console.log("THE TOKEN COOKIE: ", cookies.get("token"));
setIsClicked(false);
}
}, [isClicked]);
问题:当我单击登录按钮时,返回的令牌显然没有立即设置,因为它在第一次单击时返回未定义或空白。 当我输入错误的用户名和密码时,令牌仍然是 output
const handleLogin = (e) => {
e.preventDefault();
const csrftoken = getCookie("csrf");
const url = "http://localhost:8000/rest-auth/login/";
const cookies = new Cookies();
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({
username: username,
password: password,
}),
})
.then((response) => response.json())
.then((key) => {
setToken(key.key)
cookies.set("token", key.key);
setIsClicked(true);
})
};
您需要等待完成获取的说明
注意: setIsClicked
将名称更改为isSubmitSuccess
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.