在句柄提交中使用异步等待



我只研究了 6 个月的反应,所以也许是一个新手问题......但是我有一个句柄提交,它正在处理登录表单,尽管我想将用户(角色:用户)定向到一个页面,如果管理员(角色:管理员)到另一个页面,所以编写了以下代码检查用户的角色(这是一个测试项目,因此安全性不是特别重要。我遇到的问题(为什么它不起作用)是因为currentUser代码在获取之前运行......有没有办法在运行此代码之前使用 async await 或其他方法等待获取?

function handleSubmit(e) {
e.preventDefault();
fetch(`${process.env.REACT_APP_API}/login`, {
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
body: JSON.stringify({ email: email, password: password }),
})
.then((res) => res.json())
.then((userData) => {
setCurrentUser(userData.user);
})
.catch((error) => console.error('FETCH ERROR:', error));
currentUser.role === 'admin' ? history.push('/admin') : history.push('/');
}

提前感谢您的任何答案

Put

currentUser.role === "admin" ? history.push("/admin") : history.push("/");

.then块内部。.then块在解析承诺后执行。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

感谢您回答@daniel阳...是的,这确实有意义,尽管我已经在下面的代码中尝试过并且它不起作用,我已经添加了一个控制台日志以查看获取中的当前用户,并且它以未定义的方式返回......我不知道为什么,如果您有任何其他建议,请告诉我 - 谢谢

e.preventDefault();
fetch(`${process.env.REACT_APP_API}/login`, {
credentials: "include",
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ email: email, password: password }),
})
.then((res) => res.json())
.then((userData) => {
setCurrentUser(userData.user);
})
.then(() => {
currentUser.role === "admin"
? history.push("/admin")
: history.push("/");
})
.then(() => {
console.log("currentuser from login", currentUser);
})
.catch((error) =>
console.error("Fetch error from login handlesubmit...", error)
);```

如其他答案中所述,您需要在.then内执行重定向。您缺少的一点是,当您链接.then方法时,只有您从上一个then返回的内容才能用于下一个方法,因此您应该做的是:

.then((res) => res.json())
.then((userData) => {
setCurrentUser(userData.user);
// if you don't return this you won't have access to it in the next .then
return userData.user;
})
.then((currentUser) => {
// so now it won't be undefined since you are returning from previous .then
console.log("currentuser from login", currentUser);
return currentUser;
})
.then((currentUser) => {
currentUser.role === "admin"
? history.push("/admin")
: history.push("/");
})

您也可以在单个.then方法中完成所有这些

操作

最新更新