try and catch方法没有验证用户输入的电子邮件和密码是否存在于firebase中,但它在控制台上显示一条错误消息。
function login(email, password) {
return auth.signInWithEmailAndPassword(email, password);
}
const handleLogin = (e) => {
e.preventDefault();
try {
setError("")
login(emailRef.current.value, passwordRef.current.value);
} catch {
setError("The email or password you entered is incorrect");
}
}
对signInWithEmailAndPassword(email, password)
的调用是异步调用,并返回一个promise。
promise本质上是一个异步任务,它要么完成要么失败。在这里阅读更多关于promises的信息。
在此场景中,该函数必须联系Firebase身份验证服务器,尝试获取用户帐户,然后返回错误或将用户登录到他们的帐户。
为什么不显示错误?您的函数在收到服务器的响应之前就完成了它的执行。如果没有响应,则它不知道有错误。为了解决这个问题,你必须等待诺言来解决。为此,我建议使用async/await语法。
修改你的函数如下:
const handleLogin = async (e) => {
e.preventDefault();
try {
setError("")
await login(emailRef.current.value, passwordRef.current.value);
}catch {
setError("The email or password you entered is incorrect");
}
}