【问题标题】:React Hooks Form : undefined values on submitReact Hooks Form:提交时未定义的值
【发布时间】:2021-07-31 00:09:36
【问题描述】:

我以documentation 为例:

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

export default function App() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  console.log(watch("example")); 

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input defaultValue="test" {...register("example")} />
      <input type="submit" />
    </form>
  );
}

但在每次更改或提交时,每个字段我都会得到undefined

我尝试再次安装该库,但没有任何改变,而且到处都未定义...似乎是注册功能的问题。有人遇到同样的问题吗?

【问题讨论】:

  • 你使用的是什么版本的 react-hook 表单?
  • 您好,您可以查看react-hook-form.com/api/useform/watch。你应该在提交时手动添加你的手表值,它通常在提交中接受值
  • 我用的是6.15.5版本
  • 请更新到最新版本,例如7.4.2,v6 不以这种方式工作

标签: javascript reactjs react-hooks react-hook-form


【解决方案1】:

在 v7 中,register 的用法发生了变化,如 cmets 中所述。如果还需要使用v6,就得这样写:

function App() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  console.log(watch("example")); 

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input defaultValue="test" name="example" ref={register} />
      <input type="submit" />
    </form>
  );
}

Docs v6

【讨论】:

  • 我会检查并通知您。谢谢
  • 再次感谢。这确实是问题
【解决方案2】:

在我的情况下,我像“npm i react-hook-form”一样安装,我不知道为什么,但它安装了 ^6.15.8 版本,我将其删除并重试,然后它安装正确。因此,请尝试检查您的 react-hook-form 版本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-18
    • 2022-08-05
    • 2017-09-27
    • 2022-01-06
    • 2019-10-05
    • 1970-01-01
    • 2021-05-30
    • 2021-10-12
    相关资源
    最近更新 更多