You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Hook Form defaultValue无法接收Zustand/Prisma数据求助

问题:React Hook Form 绑定 Zustand 数据后 getValues 返回 Undefined

问题场景

用 React Hook Form 实现数据编辑/更新功能时遇到以下问题:

  • 从 Zustand 中获取数据(最初类型为any,后来改为 Prisma 定义的Report表模型类型),将其赋值给表单的defaultValue
  • 调用getValues()时返回undefined,但手动硬编码字符串或数字作为defaultValue时,getValues()能正常返回对应值
  • 调整数据类型后问题依旧,打印表单输入值仍为undefined

解决方法

问题源于首次渲染的时序问题:Zustand 的数据可能在 React Hook Form 初始化时尚未就绪,直接赋值defaultValue会导致表单初始值未正确设置。需要通过useEffect监听 Zustand 数据变化,在数据就绪后调用 React Hook Form 的reset()API 同步表单初始值。

代码示例

错误写法(直接赋值 defaultValue)

import { useForm } from "react-hook-form";
import useStore from "./store";

const EditReport = () => {
  const currentReport = useStore(state => state.currentReport);
  // 首次渲染时currentReport可能未就绪,导致defaultValues为空
  const { register, getValues } = useForm({
    defaultValues: currentReport
  });

  // 调用getValues()会返回undefined
  const handleSubmit = () => {
    console.log(getValues());
  };

  return (
    <form onSubmit={handleSubmit}>
      <input {...register("title")} />
      <button type="submit">提交</button>
    </form>
  );
};

正确写法(useEffect + reset)

import { useForm, useEffect } from "react-hook-form";
import useStore from "./store";

const EditReport = () => {
  const currentReport = useStore(state => state.currentReport);
  const { register, getValues, reset } = useForm();

  // 监听currentReport变化,数据就绪后重置表单
  useEffect(() => {
    if (currentReport) {
      reset(currentReport);
    }
  }, [currentReport, reset]);

  // 此时调用getValues()能正常获取到数据
  const handleSubmit = () => {
    console.log(getValues());
  };

  return (
    <form onSubmit={handleSubmit}>
      <input {...register("title")} />
      <button type="submit">提交</button>
    </form>
  );
};

原因说明

React Hook Form 的defaultValues仅在表单初始化时生效一次,如果此时 Zustand 的异步数据(比如从接口加载的报告数据)还未返回,currentReport为undefined,表单就会以空值初始化。而reset()API 可以在数据就绪后主动更新表单的初始值,确保表单状态与 Zustand 数据同步,之后调用getValues()就能正确获取到对应字段的值。

内容的提问来源于stack exchange,提问作者Xunter Monst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:52:35