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

React从API获取数据填充表单失败问题求助

解决React Hook Form无法填充API获取数据的表单问题

问题根源

你用了React原生的defaultValue属性,但它仅在组件首次挂载时生效。由于API请求是异步的,当数据返回时,表单已经完成初始渲染,defaultValue不会自动更新输入框内容。另外,初始状态{} as Vacation是空对象,在JS中属于真值,会导致表单提前渲染,此时editedVacation.destination可能还是undefined。

解决方案:使用React Hook Form的reset方法

React Hook Form提供的reset方法可以专门用于更新表单初始值,同步表单内部状态,让输入框正确显示异步获取的数据。

修改后的状态与请求代码

import { useForm } from "react-hook-form";

// 初始化表单钩子
const { register, handleSubmit, errors, trigger, reset } = useForm<Vacation>();
const [editedVacation, setEditedVacation] = useState<Vacation>({} as Vacation);

useEffect(() => {
  const getVacation = async () => {
    try {
      const response = await axios.get<Vacation>(
        `http://localhost:4000/api/v1/vacations/list/${id}`
      );
      const vacationData = response.data;
      setEditedVacation(vacationData);
      // 用reset同步表单初始值
      reset(vacationData);
      console.log(vacationData);
    } catch (error) {
      console.log(error);
    }
  };
  getVacation();
}, [id, reset]); // 将reset加入依赖数组

修改后的表单代码

移除defaultValue,并优化数据加载判断逻辑,确保数据完全加载后再渲染表单:

{/* 判断具体字段或对象是否有内容,避免空对象提前渲染 */}
{editedVacation.destination && (
  <form className="editVacationForm" onSubmit={handleSubmit(onSubmit)}>
    <Typography variant="h4">
      Edit Vacation{" "}
      <FontAwesomeIcon icon={faUmbrellaBeach} color="#FFC857" />
    </Typography>
    <TextField
      className="destination"
      type="text"
      label="Destination"
      {...register("destination")}
      error={!!errors.destination}
      helperText={errors.destination?.message}
      onBlur={() => trigger("destination")}
    />
    {/* 其他表单字段 */}
  </form>
)}

补充说明

如果需要更通用的加载判断(比如表单有多个字段),可以用Object.keys(editedVacation).length > 0替代editedVacation.destination,确保整个对象数据已加载完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:03:14