【发布时间】:2021-11-09 00:02:21
【问题描述】:
我只研究了 6 个月的反应,所以也许是一个新手问题....但是我有一个处理登录表单的提交,虽然我想将用户(角色:用户)定向到一个页面和如果管理员(角色:管理员)到不同的页面,所以写了下面的代码检查用户的角色(这是一个测试项目,所以安全性并不是特别重要。我遇到的问题(为什么它不工作)是因为 currentUser 代码在 fetch 之前运行...有没有办法使用 async await 或其他方式在运行此代码之前等待 fetch ?
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('/');
}
提前感谢您的任何回答
【问题讨论】:
标签: reactjs async-await