我正在使用useState设置一个状态变量,无论是否点击了recaptcha,但是当我使用setState函数时,我的验证码变量在提交时没有传递,不明白为什么,如果我删除setState,验证码变量就会传递给我的onSubmit。如果我删除setSubmitButton(false),一切都很好,不太确定为什么。
当我运行 setSubmittButton(false) 验证码在我的提交函数中受到欢迎时,当我没有它时,我在提交函数中得到了正确的验证码值。
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)
}
慕容森
相关分类