我正在使用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) }
1 回答
慕容森
TA贡献1853条经验 获得超18个赞
您应该将验证码值存储在状态变量(或 ref)中,而不是普通的 JS 变量中。普通 JS 变量将重置为组件重新呈现时(在更改状态之后)。undefinedsetSubmitButton
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");
...
}
提示:此外,请确保将 html 属性的所有匹配项替换为 。您可以使用 HTML 到 JSX 转换器来自动执行此类任务。forhtmlFor
添加回答
举报
0/150
提交
取消