【问题标题】:How to stop reloading page after submit in the react-hook-form?在 react-hook-form 中提交后如何停止重新加载页面?
【发布时间】:2023-01-04 00:15:18
【问题描述】:

我用反应挂钩形式库来验证我的表单,但我希望我的页面在提交表单后不要重新加载,以便我可以自行将用户重定向到所需的页面。例如,使用 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;

【问题讨论】:

  • 你能分享代码吗?
  • @Ingenious_Hans 已更新

标签: reactjs react-hook-form


【解决方案1】:

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

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

会变成这样:

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

【讨论】:

    【解决方案2】:

    在表单 onSubmit 函数中将 e 作为参数传递,并在该函数中写入

    e.preventDefault();
    

    【讨论】:

    • 但是 onSubmit 必须从 react-hook-form 库中获取 handleSubmit
    【解决方案3】:

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

    e.preventDefault() 
    

    【讨论】:

    • 但是 onSubmit 必须从 react-hook-form 库中获取 handleSubmit
    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

      接受的答案类型并不完全准确。我有一些打字稿错误。

      这为我修好了:

       const handleLogin = (
          data: dataType,
          e?: React.BaseSyntheticEvent // This one specifically.
        ) => {
          e?.preventDefault();     // Stop page refresh
          console.log('debug data ->', data);
        };
      

      通过调用表单上的 onSubmit 事件,如下所示:

      <form onSubmit={handleSubmit(handleGiftCardSubmit)}>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-04
        • 2013-08-18
        • 2022-07-28
        • 2013-02-11
        • 2021-11-01
        • 2015-01-17
        • 2020-10-16
        • 2018-01-19
        相关资源
        最近更新 更多