【问题标题】:Invalid Hook Call Warning on using react-hook-form使用 react-hook-form 时出现无效的挂钩调用警告
【发布时间】:2021-12-30 00:06:27
【问题描述】:

我刚开始反应并尝试运行以下代码,但收到错误消息:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

我已尝试按照以下步骤来帮助确定问题所在,但无法修复。 (我认为问题不在于第 2 点或第 3 点。) https://reactjs.org/warnings/invalid-hook-call-warning.html

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

export default function App() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);
  console.log(errors);
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input type="text" placeholder="First name" {...register("First name", {required: true, maxLength: 80})} />
      <input type="text" placeholder="Last name" {...register("Last name", {required: true, maxLength: 100})} />
      <input type="text" placeholder="Email" {...register("Email", {required: true, pattern: /^\S+@\S+$/i})} />
      <input type="tel" placeholder="Mobile number" {...register("Mobile number", {required: true, minLength: 6, maxLength: 12})} />

      <input type="submit" />
    </form>
  );
}

根据我的node_module文件夹中的项目,react和react-dom的版本都是17.0.2。

是不是我做错了什么?

非常感谢

【问题讨论】:

  • 我刚刚将您的代码复制并粘贴到沙箱中,它运行良好。因此,您共享的代码的 sn-p 可能没有任何问题。您是否检查了多个反应版本npm ls react?您的代码中是否有其他部分未表示您可能从无效位置调用钩子?
  • 感谢您查看此问题,我无法解决此问题,但我刚刚创建了另一个项目并复制了上述代码,现在可以正常工作。我不知道我之前的项目出了什么问题。
  • 这很奇怪,但也很好听。项目一切顺利!

标签: node.js reactjs react-hooks react-hook-form


【解决方案1】:

可能是您在错误目录中运行了npm install --save react-hook-form(或类似yarn),因此您的实际package.jsonpackage-lock.json 文件不包含对react-hook-form 包的引用。如果是这样,您的import 语句可能设置了对useForm 的无效引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2020-10-19
    • 2021-12-07
    • 2020-08-13
    • 1970-01-01
    相关资源
    最近更新 更多