当我注册时,如果出现错误,setstates 会起作用并显示错误消息,但如果注册成功,它不会显示任何内容,并且看起来全部重新呈现为默认值。 这是代码:
import React, { useState } from "react";
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
const SignUp = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [success, setSuccess] = useState("");
const handleSignUp = async (e) => {
e.preventDefault();
const auth = getAuth();
try {
await createUserWithEmailAndPassword(auth, email, password);
setSuccess("Sign up successful!");
setError(""); // Clear any previous error
} catch (err) {
setError("Failed to sign up: " + err.message);
setSuccess(""); // Clear any previous success message
}
};
return (
<div>
<h2>Sign Up</h2>
<form onSubmit={handleSignUp}>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<button type="submit">Sign Up</button>
</form>
{success && <div style={{ color: "green" }}>{success}</div>}
{error && <div style={{ color: "red" }}>{error}</div>}
</div>
);
};
export default SignUp;
这是默认页面: 默认
这是错误页面: 出现错误
当我单击按钮并成功注册时,它会立即再次显示默认页面,但用户实际上已添加,我在我的 firebase 控制台中看到了它: 成功
我尝试放置一个alert()来显示成功的消息,它起作用了,它显示了警报并再次重新渲染,所以我认为这可能与usestate有关
首先,您将什么作为 createUserWithEmailAndPassword 的第一个参数? 你的例子:
const handleSignUp = async (e) => {
e.preventDefault();
const auth = getAuth();
try {
await createUserWithEmailAndPassword(auth, email, password);
setSuccess("Sign up successful!");
setError(""); // Clear any previous error
} catch (err) {
setError("Failed to sign up: " + err.message);
setSuccess(""); // Clear any previous success message
}
};
检查文档,它只需要电子邮件和密码。
createUserWithEmailAndPassword ( email : string , password : string ) : Promise < UserCredential >
https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#createuserwithemailandpassword
所以我认为你总是会遇到错误,因为你输入了 3 个参数而不是 2 个。