为什么我需要按两次才能提交表格



我想提交登录表单,但我需要按两次才能完成登录表单,我不知道会发生什么。我使用的是样式组件,此按钮窗体是一个输入标记此外,我正在使用firebase挂钩我只想点击一次并提交

这是我的代码

export default function LoginForm() {
// submit
const handleLogin = (e) => {
e.preventDefault();
signInWithEmailAndPassword(email, password);
if (user) {
setTimeout(() => {
history.push(`${ROUTES.HOME}`);
}, 1000);
}
};
if (loading) {
return <Loading />;
}
return (
<FormContainer onSubmit={(e) => handleLogin(e)}>
<LogoContainer>
<img
src="https://firebasestorage.googleapis.com/v0/b/auth-c068d.appspot.com/o/instagram%2Finstagram-signup.png?alt=media&token=cdafffb1-3034-474d-be96-d507b5e416c6"
alt="instagram-logo"
/>
</LogoContainer>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
required
/>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
required
/>
<ButtonForm type="submit" name="btn-login" value="Log In" />
<p>
Don't have an account? <Link to="/signup">Sign Up</Link>
</p>
{error && <Error errorMessage={error.message} />}
</FormContainer>
);
}

这里似乎需要使用useEffect挂钩。您的handleLogin函数在每次单击时只运行一次。第一次提交时,用户未按预期定义。当你第二次点击它时,它就起作用了,因为用户是诚实的。

尝试将其从handleLogin函数中删除

if (user) {
setTimeout(() => {
history.push(`${ROUTES.HOME}`);
}, 1000);
}

然后添加一个useEffect钩子

useEffect(() => {     
if (user) {
setTimeout(() => {
history.push(`${ROUTES.HOME}`);
}, 1000);
}}, [user])

每次更改user状态后,此效果将在组件装载、上运行。(这是假设用户处于使用反应状态,因为我看不出user是从哪里来的(

将按钮类型从type="submit"更改为type="button",并使用onCkick={() => clickHandler()}处理点击

最新更新