亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

useState with react 給我問題 onChange 處理程序

useState with react 給我問題 onChange 處理程序

慕標5832272 2022-09-02 17:05:03
我正在使用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


查看完整回答
反對 回復 2022-09-02
  • 1 回答
  • 0 關注
  • 81 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號