在 react-hook-form 中提交后如何停止重新加载页面?

How to stop reloading page after submit in the react-hook-form?

我使用 react-hook-form 库来验证我的表单,但我希望我的页面在提交表单后不要重新加载,以便我可以将用户重定向到我自己想要的页面。例如,使用 react-router-dom 库中的 navigate 钩子。如何停止页面重新加载?

我的代码:

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;

并尝试在 handleSubmit 函数的开头使用:

e.preventDefault() 

在表单 onSubmit 函数中将 e 作为参数传递,并在该函数内部写入 [​​=11=]

e.preventDefault();

添加event.preventDefault();在 handleLogin 函数上 :) 哦,你还需要一个事件参数


你有这个处理程序,只需将事件作为第二个参数,这个:

const handleLogin: SubmitHandler<IAuthFormFields> = ({email, pass}) => {....

会变成这样:

const handleLogin: SubmitHandler<IAuthFormFields> = ({email, pass}, e?: Event) => {    
 e.preventDefault()
 signInWithEmailAndPassword(auth, email, pass)
              .then(async (userCredential) => {....