Js必须按两次按钮才能注册 [英] React.js Have to press button twice for register
本文介绍了Js必须按两次按钮才能注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个网站,我在那里建立了一个登录系统。
Register.jsx
export default function Register() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [username, setUsername] = useState("");
const history = useHistory();
const emailRef = useRef();
const passwordRef = useRef();
const usernameRef = useRef();
const handleStart = () => {
setEmail(emailRef.current.value);
};
const handleFinish = async (e) => {
e.preventDefault();
setUsername(usernameRef.current.value);
setPassword(passwordRef.current.value);
try {
await axios.post("auth/register", {username, email, password });
history.push("/login");
} catch (err) {}
};
return (
.......
{!email ? (
<div className="input">
<input type="email" placeholder="email address" ref={emailRef} />
<button className="registerButton" onClick={handleStart}>
Get Started
</button>
</div>
) : (
<form className="input">
<input type="username" placeholder="username" ref={usernameRef} />
<input type="password" placeholder="password" ref={passwordRef} />
<button className="registerButton" onClick={handleFinish}>
Start
</button>
</form>
)}
</div>
</div>
);
}
我的身份验证路由
router.post("/register", async (req, res) => {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: CryptoJS.AES.encrypt(
req.body.password,
process.env.SECRET_KEY
).toString(),
});
try {
const user = await newUser.save();
res.status(201).json(user);
} catch (err) {
res.status(500).json(err);
}
});
当我第一次点击该按钮时,控制台中的有效负载如下所示:
email: "test9@gmail.com"
password: ""
username: ""
它失败了。但当我再按一次时:
email: "test9@gmail.com"
password: "123456"
username: "test9"
它起作用了,所有东西都在我的数据库里。这会是什么问题呢?我几乎什么都试过了。
推荐答案
您在更新状态值后直接使用它们。它们在下一次渲染单元之前不会反映更新的值。
这就是为什么电子邮件的值是正确的。其余的都是空白的。电子邮件已在上一周期中设置为
setEmail(emailRef.current.value);
用这个更新您的代码。它应该可以工作:
setUsername(usernameRef.current.value);
setPassword(passwordRef.current.value);
try {
await axios.post("auth/register", {usernameRef.current.value, email, passwordRef.current.value });
history.push("/login");
} catch (err) {}
这篇关于Js必须按两次按钮才能注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文