正文从这开始~

总览

导致"Invalid hook call. Hooks can only be called inside the body of a function component"错误的有多种原因:

  1. reactreact-dom的版本不匹配。
  2. 在一个项目中有多个react包版本。
  3. 试图将一个组件作为一个函数来调用,例如,App()而不是<App />
  4. 在类里面使用钩子,或者在不是组件或自定义钩子的函数中使用钩子。

版本匹配

在项目的根目录下打开终端,更新reactreact-dom包的版本,确保版本是相匹配的,并且没有使用过时的版本。

# ️ with NPM
npm install react@latest react-dom@latest # ️ ONLY If you use TypeScript
npm install --save-dev @types/react@latest @types/react-dom@latest # ---------------------------------------------- # ️ with YARN
yarn add react@latest react-dom@latest # ️ ONLY If you use TypeScript
yarn add @types/react@latest @types/react-dom@latest --dev

如果错误仍存在,尝试删除node_modules以及package-lock.json(不是package.json)文件,重新运行npm install 并重启你的IDE。

这个错误通常是由于在同一个项目中拥有多个版本的react造成的。

# ️ delete node_modules and package-lock.json
rm -rf node_modules
rm -f package-lock.json # ️ clean npm cache
npm cache clean --force npm install

如果错误仍然存在,请确保重启了IDE和开发服务。VSCode经常出现故障,需要重启。

调用组件

这里有另一个示例,用来展示错误是如何发生的。

// App.js
import {useState} from 'react'; // ️ Don't call components as functions ️
App(); export default function App() {
/**
* ️ Warning: 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
*/
const [count, setCount] = useState(0); return (
<div>
<h1>Hello world</h1>
</div>
);
}

问题在于,我们将App组件作为函数进行调用。

你应该只使用具有JSX语法的组件。比如:<App country="Austria" age="30" />,而不是App({country: 'Austria', age: 30})

确保你没有在一个类组件,或一个既不是组件也不是自定义钩子的函数里面调用钩子。

如果你有一个类,请将其转换为能够使用钩子的函数。

下面是一个例子,说明在一个既不是组件也不是自定义钩子的函数中是如何引起错误的。

// App.js
import {useState, useEffect} from 'react'; // ️ not a component nor custom hook
// so it can't use hooks
function counter() {
const [count, setCount] = useState(0); useEffect(() => {
console.log('hello world');
}, []);
}

counter函数以小写的c开头,所以它不被React认为是一个组件。因为所有的组件名称必须以大写字母开头。它同样也不是自定义钩子,因为其名称没有以use开头,比如说useCounter

我们只能在函数组件或自定义钩子里面使用钩子,所以能够使用钩子的一个方法是将counter重命名为useCounter

import {useState, useEffect} from 'react';

function useCounter() {
const [count, setCount] = useState(0); useEffect(() => {
console.log('hello world');
}, []);
}

现在React认为useCounter是一个自定义钩子,并允许我们在里面使用钩子。

就像文档中所说的那样:

  • 只从React函数组件或自定义钩子中调用Hook
  • 只在最顶层使用 Hook
  • 不要在循环,条件或嵌套函数中调用 Hook
  • 确保总是在你的 React 函数的最顶层以及任何 return 之前使用 Hook

React报错之Invalid hook call的更多相关文章

  1. Jade报错:Invalid indentation,you can use tabs or spaces but not both问题

    现象:通过html生成jade文件之后,更改jade文件时,语句没什么问题的情况下,jade文件编译不通过,报错:Invalid indentation,you can use tabs or spa ...

  2. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  3. mysql创建表时,设置timestamp DEFAULT NULL报错1067 - Invalid default value for 'updated_at'

    问题背景: 线上的linux服务器上的mysql服务器中导出数据库的结构.想要在本地创建一个测试版本 导出后再本地mysql上运行却报错   1067 - Invalid default value ...

  4. 数据库查询语句报错-ORA-00911: invalid character

    数据库查询语句报错-ORA-00911: invalid character 根据自己经验总结下: 1.都是分号惹的祸,有时候sql语句后面有分好导致这种错误 2.还有一种是从别处copy过来的sql ...

  5. CocoaPods pod install的时候报错:invalid byte sequence in UTF-8 (ArgumentError)解决办法

    CocoaPods pod install的时候报错:invalid byte sequence in UTF-8 (ArgumentError)解决办法: 基本可以确定是Podfile中的内容编码有 ...

  6. ssh调用matplotlib绘图报错RuntimeError: Invalid DISPLAY variable

    1.问题:在本地用matplotlib绘图可以,但是在ssh远程绘图的时候会报错 RuntimeError: Invalid DISPLAY variable 2.原因:matplotlib的默认ba ...

  7. golang解析json报错:invalid character '\x00' after top-level value

    golang解析json报错:invalid character '\x00' after top-level value 手动复制字符串:{"files":["c:/t ...

  8. mybatis报错:Invalid bound statement (not found)

    mybatis报错:Invalid bound statement (not found)的原因很多,但是正如报错提示一样,找不到xml中的sql语句,报错的情况分为三种: 第一种:语法错误 Java ...

  9. git commit -m "XX"报错 pre -commit hook failed (add --no-verify to bypass)问题

    在同步本地文件到线上仓库的时候 报错 pre -commit hook failed (add --no-verify to bypass) 当你在终端输入git commit -m "xx ...

随机推荐

  1. 【Redis】skiplist跳跃表

    有序集合Sorted Set zadd zadd用于向集合中添加元素并且可以设置分值,比如添加三门编程语言,分值分别为1.2.3: 127.0.0.1:6379> zadd language 1 ...

  2. 新上线!3D单模型轻量化硬核升级,G级数据轻松拿捏!

    "3D模型体量过大.面数过多.传输展示困难",用户面对这样的3D数据,一定不由得皱起眉头.更便捷.快速处理三维数据,是每个3D用户对高效工作的向往. 在老子云最新上线的单模型轻量化 ...

  3. Linux-Centos快速安装Docker

    卸载之前的docker sudo yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docker-l ...

  4. 『忘了再学』Shell流程控制 — 38、while循环和until循环介绍

    目录 1.while循环 2.until循环 1.while循环 对while循环来讲,只要条件判断式成立,循环就会一直继续,直到条件判断式不成立,循环才会停止.和for循环的第二种格式for((初始 ...

  5. HTML知识点概括——一篇文章带你完全掌握HTML

    HTML知识点概括 前端三件套分别是HTML3,CSS5,JavaScript 稍微介绍一下W3C标准: 结构化标准语言(HTML) 表现标准语言(CSS) 行为标准(DOM,JavaScript) ...

  6. java的Test 如何使用@Autowired注解

    1.配置来至bean.xml @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "class ...

  7. @ConditionalOnMissingBean 如何实现覆盖第三方组件中的 Bean

    1. 自定义一个简单 spring-boot 组件 创建 olive-starter 项目 对应的 pom.xml文件如下 <project xmlns="http://maven.a ...

  8. C语言课堂--现代编译环境搭建[2020年7月]

    看过了很多专家吐槽目前的大学c语言教学问题多多: 教材难懂,消磨了学生的兴趣: 环境老旧,都2020了还有在用VC6甚至TurboC 2.0,语法不规范. 轮到自己上课,心想可不能再继续这样的c语言课 ...

  9. OI的起点

    经过几周的复制与粘贴建设与测试,我终于有了自己的博客! 本蒟蒻目前准初二,就读于深圳SFLS. 我以后会在这里发一些文章,希望大家多多支持.

  10. 题解 洛谷 P2388 阶乘之乘

    目录 简要题意 题解 主要思路 一个 \(\omega(n)\) 的算法 一个 \(O(\log n)\) 的算法 一个算法 代码 算法 \(1\)(\(\omega(n)\)) 算法 \(2\) 算 ...