提问人:Nick O. 提问时间:11/12/2023 最后编辑:Nick O. 更新时间:11/15/2023 访问量:52
React Hook Form isSubmitSuccessful 首次提交时返回 false
React Hook Form isSubmitSuccessful returning false on first submission
问:
我正在使用带有 EmailJS 的 React Hook Form 为我的网站创建一个表单。我正在访问“isSubmitSuccessful”属性以动态显示对话框弹出窗口(使用无头 UI 对话框组件)。当我尝试发送表单时,在第一次尝试时,即使表单有效,isSubmitSuccessful 也会返回 false。EmailJS sendForm 函数不会引发错误并成功返回。注意:我也在使用 reCAPTCHA v2,这可能会导致问题。
当我故意将 reCAPTCHA 复选框留空以失败提交时,表单将在第二次尝试时成功发送。但是,表单提交在第一次尝试时持续失败。我还试图阻止默认行为(e.preventDefault),但这并没有解决它。
我无法找到太多有关这方面的信息,如果有人有建议,我将不胜感激。
这是我的代码(请注意,我使用的是Next.js 13):
"use client";
import React, { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import emailjs from "@emailjs/browser";
import styles from "./Contact.module.css";
import ReCAPTCHA from "react-google-recaptcha";
import DialogPopup from "../shared/Dialog/Dialog";
function ContactForm() {
const [dialogIsOpen, setDialogIsOpen] = useState(false);
const form = useRef();
const recaptchaRef = useRef(null);
const {
register,
handleSubmit,
reset,
formState: { isSubmitSuccessful },
} = useForm({
defaultValues: {
user_name: "",
user_email: "",
message: "",
},
});
const openDialog = () => {
setDialogIsOpen(true);
};
const closeDialog = () => {
reset();
recaptchaRef.current.reset();
setDialogIsOpen(false);
};
const onSubmit = (data, e) => {
e.preventDefault();
emailjs
.sendForm(
"contact_service",
"contact_form",
form.current,
// Removed key for security
)
.then(
(result) => {
console.log("isSubmitSuccessful", isSubmitSuccessful);
console.log("SUCCESS!");
console.log(result.text);
},
(error) => {
console.log("isSubmitSuccessful", isSubmitSuccessful);
console.log("FAILED...");
console.log(error.text);
alert("Please verify that you are a human.");
}
);
if (isSubmitSuccessful) {
openDialog();
}
};
return (
<form
className={styles["contact-form"]}
onSubmit={handleSubmit(onSubmit)}
ref={form}
>
<input
className={styles["contact-form-field"]}
type="text"
placeholder="Name"
name="user_name"
{...register("user_name", { required: true, maxLength: 120 })}
/>
<input
className={styles["contact-form-field"]}
type="text"
placeholder="Email"
name="user_email"
{...register("user_email", { required: true, pattern: /^\S+@\S+$/i })}
/>
<textarea
className={styles["contact-form-field"]}
type="text"
placeholder="Additional Information"
name="message"
{...register("message", {
required: false,
maxLength: 250,
})}
/>
<ReCAPTCHA
sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_KEY}
ref={recaptchaRef}
/>
<input className={styles.submit} type="submit" value="Send" />
<DialogPopup
title="Message Sent!"
description="Thank you for your inquiry"
buttonText="Finish"
isOpen={dialogIsOpen}
closeDialog={closeDialog}
/>
</form>
);
}
export default ContactForm;
编辑:
在通读了 RHF 文档并运行了一些测试后,它似乎与将 EmailJS 与 RHF 一起使用有关。我不认为RHF可以识别EmailJS sendForm方法,因此当handleSubmit调用此方法时,它不会传递“isSubmitSuccessful”。我移动了 openDialog() 以在 sendForm 成功时调用。这似乎正在起作用。
答: 暂无答案
评论