繁体   English   中英

useState with react 给我关于 google recaptcha 的 onChange 处理程序的问题

[英]useState with react giving me issues with onChange handler for google recaptcha

我正在使用 useState 设置一个 state 变量,无论是否点击了验证码,但是当我使用 setState function 时,我的验证码变量在提交时没有通过,不明白为什么,如果我删除了 setState 验证码变量很好地传递给我的 onSubmit。 如果我删除 setSubmitButton(false) 一切正常,不太清楚为什么。

当我在我的提交 function 中运行 setSubmittButton(false) 验证码时,当我没有它时,我在提交 function 中得到正确的验证码值。

import React, { useState } from "react"
import { useForm } from "react-hook-form"
import ReCAPTCHA from "react-google-recaptcha"

const ContactForm = () => {
  const { register, handleSubmit, watch, errors } = useForm()

  const isBrowser = typeof window !== `undefined`
  let location
  if (isBrowser) {
    location = window.location.hostname
  }
  let fetchUrl
  if (location === "localhost") {
    fetchUrl = `http://localhost:8888/.netlify/functions/contact`
  } else if (location === "fsdf.gtsb.io") {
    fetchUrl = `https://fdsfd/.netlify/functions/contact`
  } else {
    fetchUrl = "/.netlify/functions/contact"
  }

  console.log(fetchUrl)

  const onSubmit = async data => {
    setLoading(true)
    console.log(captcha, "captcha value final")
    const response = await fetch(fetchUrl, {
      method: "POST",
      body: JSON.stringify({ data, captcha: captcha }),
    })
      .then(response => response.json())
      .then(data => {
        console.log(data)
        if (data.captcha === false) {
          setCaptchaFailed(true)
        }
      })
      .catch(error => {
        console.error("Error:", error)
      })
  }
  const [submitButton, setSubmitButton] = useState(true)
  const [loading, setLoading] = useState(false)
  const [captchaFailed, setCaptchaFailed] = useState(false)

  let captcha

  function onChange(value) {
    setSubmitButton(false) // IF I REMOVE THIS LINE EVERYTHING WORKS FINE ******
    console.log("Captcha value:", value)
    captcha = value
  }

  function error(value) {
    alert(value)
  }

  return (
    <>
      {/* "handleSubmit" will validate your inputs before invoking "onSubmit" */}
      {!loading ? (
        <form onSubmit={handleSubmit(onSubmit)}>
          <div>
            <label for="name">Name</label>
            <input name="name" ref={register({ required: true })} />
            {errors.name && <span>This field is required</span>}
          </div>
          <div>
            <label for="email">Email</label>
            <input
              type="email"
              name="email"
              ref={register({ required: true })}
            />
            {errors.email && <span>This field is required</span>}
          </div>
          <div>
            <label for="message">Message</label>
            <textarea name="message" ref={register({ required: true })} />
            {errors.message && <span>This field is required</span>}
          </div>
          <ReCAPTCHA
            sitekey="fdsfsa"
            onChange={onChange}
            onErrored={error}
          />
          <input
            type="submit"
            className={submitButton ? "disabled" : ""}
            disabled={submitButton ? "disabled" : ""}
          />
        </form>
      ) : (
        <>
          {captchaFailed ? (
            <>
              <p>Captcha Verification Failed</p>
            </>
          ) : (
            <h1>Loading</h1>
          )}
        </>
      )}
    </>
  )
}

export default ContactForm

您应该将验证码值存储在 state 变量(或 ref)中,而不是普通的 JS 变量中。 当组件重新渲染时(在setSubmitButton更改状态之后),普通 JS 变量将重置为undefined


const [ captchaValue, setCaptchaValue ] = useState(null);

function onChange(value) {
    setSubmitButton(false); 
    console.log("Captcha value:", value);
    setCaptchaValue(value);
}

const onSubmit = async data => {
    setLoading(true)
    console.log(captchaValue, "captcha value final");
    ...
}

提示:另外,确保将所有出现的for html 属性替换为htmlFor 您可以使用HTML-to-JSX 转换器来自动执行此类任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM