【问题标题】:Invalid hook call. Hooks can only be called inside of the body of a function component-formik无效的挂钩调用。 Hooks 只能在函数体内部调用 component-formik
【发布时间】:2021-08-13 12:46:10
【问题描述】:

在一个简单的反应应用程序中,我使用了 formik hook useFormik,但浏览器抱怨它在错误的地方使用。 这是我所做的:

import React from 'react';
 import { useFormik } from 'formik';
 
 const SignupForm = () => {
   // Pass the useFormik() hook initial form values and a submit function that will
   // be called when the form is submitted
   const formik = useFormik({
     initialValues: {
       email: '',
     },
     onSubmit: values => {
       alert(JSON.stringify(values, null, 2));
     },
   });
   return (
     <form onSubmit={formik.handleSubmit}>
       <label htmlFor="email">Email Address</label>
       <input
         id="email"
         name="email"
         type="email"
         onChange={formik.handleChange}
         value={formik.values.email}
       />
 
       <button type="submit">Submit</button>
     </form>
   );
 };
 export default SignupForm;

然后我使用了 useState 钩子,它工作正常,但这个在抱怨。 投诉是:

错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。这可能是由于以下原因之一:

  1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本 有关如何调试和解决此问题的提示,请参阅 https://reactjs.org/link/invalid-hook-call

【问题讨论】:

  • 从您的代码中可以清楚地看出,您并没有违反钩子的规则,因为它是在组件顶部定义的。所以问题可能是原因 #1 或 #3
  • 但是 useState 钩子工作正常,这意味着如果有 1 或 3 的东西,我们可能会看到其他钩子也不起作用
  • 那么问题可能出在 formik 包上。卸载并重新安装它

标签: javascript reactjs react-hooks formik


【解决方案1】:

我遇到了类似的问题。结果发现这个包根本没有安装,但是 typescript 没有检测到它丢失了。

试试

rm -rf node_modules
rm package-lock.json
npm i 
npm i formik

然后检查你是否在 package.json 中有它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2019-12-12
    • 2022-01-25
    • 1970-01-01
    • 2021-12-18
    • 2020-07-22
    相关资源
    最近更新 更多