已完成React Hook Form表单验证,如何提交数据至Firebase数据库?
React Hook Form 提交数据到 Firebase 实时数据库问题解决
核心问题
已通过 React Hook Form(简称 RHF)实现表单验证,希望直接使用 RHF 存储的验证后数据提交至 Firebase 实时数据库,避免使用 useState 造成数据覆盖,但当前提交功能无法正常运行。
代码中的关键错误
- 提交逻辑冲突:表单的
onSubmit绑定了handleSubmit(onSubmit),但提交按钮又额外添加了onClick={postData},导致提交逻辑混乱,且postData无法获取到 RHF 的验证后数据。 - Fetch 参数拼写错误:请求配置中的
header应为复数headers,否则请求头无法被正确识别。 - 数据传递路径错误:单独定义的
postData函数无法直接获取 RHF 的表单数据,必须借助handleSubmit回调传入的验证后数据。
修正后的完整代码
import React from "react"; import "./App.css"; import { useForm } from "react-hook-form"; import classNames from "classnames"; function App() { const { register, handleSubmit, formState: { errors } } = useForm(); // 将 Firebase 提交逻辑整合到 RHF 的提交回调中 const onSubmit = async (data) => { try { const res = await fetch("https://test1-5022f-default-rtdb.firebaseio.com/reactformData.json", { method: "POST", headers: { // 修正拼写错误:header → headers "content-type": "application/json", }, body: JSON.stringify(data) // 直接传入 RHF 验证后的完整数据 }); res.ok ? console.log("数据提交成功") : console.error("数据提交失败"); } catch (error) { console.error("请求出错:", error); } }; return ( <div> <div className="container"> <div className="form-group my-3 "> {/* 表单提交完全由 RHF 的 handleSubmit 处理 */} <form name="Registration_form" id="Form" onSubmit={handleSubmit(onSubmit)}> <div className="form-group my-3"> <label htmlFor="name">Name:</label> <input type="text" name="Name" id="Name" className={classNames("form-control", {"is-invalid": errors.Name})} autoComplete="off" {...register('Name', { required: true, maxLength: 15, pattern: /^[A-Za-z]+$/ })} /> <span id="name" className="text-danger fw-bold"> {errors.Name?.type === "required" && "This field is required"} </span> <span id="name" className="text-danger fw-bold"> {errors.Name?.type === "maxLength" && "Length Should be less than 15"} </span> <span id="name" className="text-danger fw-bold"> {errors.Name?.type === "pattern" && "Digits are not allowed"} </span> </div> <div className="form-group my-3"> <label htmlFor="email">Email: </label> <input type="email" // 改为 email 类型,符合语义并获得原生基础验证 name="email" id="email" className={classNames("form-control", {"is-invalid": errors.email})} placeholder="email@example.com" autoComplete="off" {...register('email', { required: true, pattern: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, })} /> <span id="mail" className="text-danger fw-bold"> {errors.email?.type === "required" && "Email is required"} </span> <span id="mail" className="text-danger fw-bold"> {errors.email?.type === "pattern" && "Invalid format"} </span> </div> {/* 移除冗余的 onClick 事件,由表单 onSubmit 统一处理 */} <input type="submit" id="submit" value="submit" className="btn btn-success my-3" /> </form> </div> </div> </div> ); } export default App;
关键修正说明
- 整合提交逻辑:将 Firebase 提交代码直接写入
handleSubmit的回调函数中,该回调会在表单验证通过后自动接收 RHF 收集的完整验证数据,无需额外使用useState存储数据。 - 修正请求参数:将
header改为headers,确保请求头被正确解析,Firebase 能识别 JSON 格式的请求体。 - 移除冗余事件:删除提交按钮的
onClick绑定,避免与表单onSubmit冲突,保证只有在表单验证通过后才执行提交操作。 - 语义化优化:将邮箱输入框类型改为
email,既符合 HTML 语义,也能获得浏览器原生的基础格式验证补充。
内容的提问来源于stack exchange,提问作者Shaheer Ahmed
相关产品推荐
相关产品推荐

