[英]How to stop reloading page after submit in the react-hook-form?
I use the react-hook-form library to validate my forms, but I want my page not to reload after submitting the form so that I can redirect the user to the desired page on my own.我使用react-hook-form库来验证我的 forms,但我希望我的页面在提交表单后不要重新加载,以便我可以自行将用户重定向到所需的页面。 For example, using the
navigate
hook from the react-router-dom library.例如,使用react-router-dom库中的
navigate
挂钩。 How to stop page reloading?如何停止页面重新加载?
My code:我的代码:
import React from 'react';
import {signInWithEmailAndPassword, updateCurrentUser} from "firebase/auth";
import {auth} from "../firebase";
import {Link, useLocation, useNavigate} from "react-router-dom";
import styles from "./elements.module.css";
import {SubmitHandler, useForm} from "react-hook-form";
import {IAuthFormFields} from "../types";
import cn from "classnames";
type locationState = { from: string };
const SignIn = () => {
const navigate = useNavigate()
const location = useLocation();
const fromPage = (location.state as locationState)?.from ?? '/';
const {
register,
formState: { errors },
handleSubmit,
setError
} = useForm<IAuthFormFields>({
mode: 'onBlur'
});
const handleLogin: SubmitHandler<IAuthFormFields> = ({email, pass}) => {
signInWithEmailAndPassword(auth, email, pass)
.then(async (userCredential) => {
const {user} = userCredential;
await updateCurrentUser(auth, user);
navigate(fromPage);
});
}
return (
<form onSubmit={handleSubmit(handleLogin)}>
<fieldset className={"flex flex-col items-center"}>
<h1 className={"text-2xl font-medium"}>Sign In</h1>
<div className={"flex flex-col w-full my-3"}>
<input
type="email"
{...register('email', {
required: true,
pattern: {
value: /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/,
message: 'Invalid email'
}
})}
placeholder="Email"
className={cn(styles.input, "my-3")}
/>
{errors?.email && <span className={styles.msg_error} >{errors.email.message}</span>}
<input
type="password"
{...register('pass', {
required: true,
})}
placeholder="Password"
className={cn(styles.input, "my-3")}
/>
{errors?.pass && <span className={styles.msg_error} >{errors.pass.message}</span>}
<button className={cn(styles.btn, "my-3")} >
Sign In
</button>
</div>
</fieldset>
</form>
);
};
export default SignIn;
According to documentation ( https://react-hook-form.com/api/useform/handlesubmit/ ) - the method expects a SubmitHandler callback argument (named "a successful callback.)根据文档( https://react-hook-form.com/api/useform/handlesubmit/ ) - 该方法需要一个 SubmitHandler 回调参数(名为“成功的回调。)
((data: Object, e?: Event) => void, (errors: Object, e?: Event) => void) => Function ((data: Object, e?: Event) => void, (errors: Object, e?: Event) => void) => Function
You have this handler, just take the event as the 2nd argument, this one:你有这个处理程序,只需将事件作为第二个参数,这个:
const handleLogin: SubmitHandler<IAuthFormFields> = ({email, pass}) => {....
Will turn into this:会变成这样:
const handleLogin: SubmitHandler<IAuthFormFields> = ({email, pass}, e?: Event) => {
e.preventDefault()
signInWithEmailAndPassword(auth, email, pass)
.then(async (userCredential) => {....
并尝试在您的 handleSubmit 函数的开头使用:
e.preventDefault()
将 e 作为参数传递给 onSubmit 函数并在该函数内部写入
e.preventDefault();
add event.preventDefault();添加 event.preventDefault(); on the handleLogin function :) oh and you also need a event parameter
在handleLogin函数上:)哦,你还需要一个事件参数
The accepted answer types are not entirely accurate.接受的答案类型并不完全准确。 I had some typescript errors.
我有一些 typescript 错误。
This fixed it for me:这为我修好了:
const handleLogin = (
data: dataType,
e?: React.BaseSyntheticEvent // This one specifically.
) => {
e?.preventDefault(); // Stop page refresh
console.log('debug data ->', data);
};
By calling the onSubmit event on the form like so:通过调用表单上的 onSubmit 事件,如下所示:
<form onSubmit={handleSubmit(handleGiftCardSubmit)}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.