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

React使用react-hook-form时setState更新input值无法传入formData问题

问题根因

你给input同时绑定了react-hook-form的register返回方法和自定义的onChange、value属性,自定义属性覆盖了register内部的状态更新逻辑,所以当你用setSoluteState/setSolventState更新值的时候,react-hook-form内部管理的表单状态没有同步更新,提交时拿到的data自然是空的。而手动输入时,register的onChange和你自定义的onChange刚好都触发,所以能正常拿到值。

另外你原代码中把FormData实例的创建写在了组件顶层,每次组件重新渲染都会生成新的空实例,最好把这行代码移到onSubmit函数内部,避免不必要的实例创建。


解决方案

方案1:删掉自定义状态绑定(最推荐)

react-hook-form本身就可以管理表单状态,不需要额外写useState维护输入值,修改后代码如下:

const FirstProject = () => {
  const [fetchData, setFetchData] = useState("");
  const [Error, setError] = useState(null);

  const { register, handleSubmit, control } = useForm({
    defaultValues: {
      solute: "",
      solvent: "",
    },
  });

  const onSubmit = (data) => {
    const formData = new FormData();
    formData.set("solute", data.solute);
    formData.set("solvent", data.solvent);

    fetch("https://flask-api-test1.herokuapp.com/predict", {
      method: "post",
      body: formData,
    })
      .then((res) => res.json())
      .then((result) => {
        setFetchData(result.result.predictions);
      })
      .catch((err) => {
        console.log(data);
        setError(err.error);
        console.log(err);
      });
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("solute")}
        placeholder="Solute"
      />
      <input
        {...register("solvent")}
        placeholder="Solvent"
      />
      <input type="submit" />
    </form>
  )
}

方案2:保留自定义state,同步更新react-hook-form状态

如果业务逻辑确实需要单独维护输入值的state,可以从useForm中导出setValue方法,在自定义onChange中同时更新两边的状态:

const FirstProject = () => {
  const [solutestate, setSoluteState] = useState("");
  const [solventstate, setSolventState] = useState("");
  const [fetchData, setFetchData] = useState("");
  const [Error, setError] = useState(null);

  const { register, handleSubmit, control, setValue } = useForm({
    defaultValues: {
      solute: "",
      solvent: "",
    },
  });

  const onSubmit = (data) => {
    const formData = new FormData();
    formData.set("solute", data.solute);
    formData.set("solvent", data.solvent);

    fetch("https://flask-api-test1.herokuapp.com/predict", {
      method: "post",
      body: formData,
    })
      .then((res) => res.json())
      .then((result) => {
        setFetchData(result.result.predictions);
      })
      .catch((err) => {
        console.log(data);
        setError(err.error);
        console.log(err);
      });
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("solute")}
        placeholder="Solute"
        onChange={(e) => {
          const val = e.target.value
          setSoluteState(val)
          setValue("solute", val) // 同步更新react-hook-form内部状态
        }}
        value={solutestate}
      />
      <input
        {...register("solvent")}
        placeholder="Solvent"
        onChange={(e) => {
          const val = e.target.value
          setSolventState(val)
          setValue("solvent", val) // 同步更新react-hook-form内部状态
        }}
        value={solventstate}
      />
      <input type="submit" />
    </form>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:06:01