【问题标题】:Why won't the form state visibly change within the submit button using react form hook?为什么使用反应表单钩子在提交按钮中表单状态不会明显改变?
【发布时间】:2022-01-05 22:19:57
【问题描述】:

所以我有一个使用react-hook-form 的注册表单,我想禁用submit input 并显示“正在登录...”消息。我已经控制台记录了渲染中的isSubmitting 值,当我提交时显示true,然后不久之后显示false,但是表单中的submit button 永远不会更新以反映isSubmitting 状态。

我做错了什么? Here is the React Hook Form useFormState docs

据我所知,它应该可以工作?

提前致谢。

import { useState } from "react"
import { useForm, useFormState } from "react-hook-form"
import useAuth from "Hooks/useAuth"

const SignInForm = () => {
  const [firebaseError, setFirebaseError] = useState(null)
  const { signIn } = useAuth()
  const {
    register,
    handleSubmit,
    resetField,
    control,
    formState: { errors },
  } = useForm()

  const { isSubmitting, isValidating } = useFormState({ control })

  const onSubmit = (data) => {
    signIn(data.email, data.password)
      .then((response) => console.log(response))
      .catch((error) => {
        let message = null

        if (error.code === "auth/too-many-requests") {
          message =
            "Too many unsuccessful attempts, please reset password or try again later"
        }

        if (error.code === "auth/wrong-password") {
          message = "Incorrect password, please try again"
        }

        if (error.code === "auth/user-not-found") {
          message = "User does not exist, please try again"
        }

        resetField("password")
        setFirebaseError(message)
      })
  }

  return (
    <form
      className="signupForm"
      onSubmit={handleSubmit(onSubmit)}
      autoComplete="off"
    >
      {console.log(isSubmitting)}
      {firebaseError && (
        <p className="form-top-error has-text-danger">{firebaseError}</p>
      )}

      <div className="field">
        <input
          type="text"
          className="input formInput"
          placeholder="Email"
          {...register("email", {
            required: {
              value: true,
              message: "Field can not be empty",
            },
            pattern: {
              value:
                /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
              message: "Invalid email",
            },
          })}
        />
        {errors.email && (
          <span className="is-block has-text-danger is-size-7">
            {errors.email?.message}
          </span>
        )}
      </div>
      <div className="field">
        <input
          type="password"
          className="input formInput"
          placeholder="Password"
          {...register("password", {
            required: "Field can not be empty",
            minLength: {
              value: 6,
              message: "Must be longer than 6 characters",
            },
          })}
        />
        {errors.password && (
          <span className="is-block has-text-danger is-size-7">
            {errors.password?.message}
          </span>
        )}
      </div>
      <input
        type="submit"
        className="button is-info"
        value={isSubmitting ? "Signing In..." : "Sign In"}
        disabled={isSubmitting}
      />
    </form>
  )
}

export default SignInForm

【问题讨论】:

  • 你的onSubmit应该是一个异步函数吗?

标签: reactjs forms react-hooks react-hook-form


【解决方案1】:

我认为您需要重构您的 onSubmit 函数以使其成为 async 以便在您的 signIn 调用期间 isSubmitting 将保持 true

const onSubmit = async (data) => {
    await signIn(data.email, data.password)
      .then((response) => console.log(response))
      .catch((error) => {
        let message = null

        if (error.code === "auth/too-many-requests") {
          message =
            "Too many unsuccessful attempts, please reset password or try again later"
        }

        if (error.code === "auth/wrong-password") {
          message = "Incorrect password, please try again"
        }

        if (error.code === "auth/user-not-found") {
          message = "User does not exist, please try again"
        }

        resetField("password")
        setFirebaseError(message)
      })
  }

【讨论】:

  • 感谢您的回复,谢谢。不幸的是,这并没有解决它
  • 似乎有效!我不得不重新启动服务器,不知道那里发生了什么 :) 谢谢!
猜你喜欢
  • 2021-12-20
  • 2021-12-13
  • 2022-08-18
  • 2020-05-18
  • 2020-06-11
  • 2021-08-25
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
相关资源
最近更新 更多