正文从这开始~

总览

当我们尝试在类组件中使用useState 钩子时,会产生"React hook 'useState' cannot be called in a class component"错误。为了解决该错误,请将类组件转换为函数组件。因为钩子不能在类组件中使用。

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

// App.js
import {useState, useEffect} from 'react'; class Example {
render() {
// ️ React Hook "useState" cannot be called in a class component.
// React Hooks must be called in a React function component or a custom React Hook function.
const [count, setCount] = useState(0); // ️ React Hook "useEffect" cannot be called in a class component.
// React Hooks must be called in a React function component or a custom React Hook function.
useEffect(() => {
console.log('hello world');
}, []); return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
}

导致这个错误的原因是,钩子只能在函数组件或自定义钩子中使用,而我们正试图在一个类中使用钩子。

函数组件

解决该错误的一种方法是,将类组件转换为函数组件。

// App.js
import {useState, useEffect} from 'react'; export default function App() {
const [count, setCount] = useState(0); useEffect(() => {
console.log('hello world');
}, []); return (
<div>
<h2>Count {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

就像文档中所说的那样:

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

类组件中使用setState()

另外,我们可以使用一个类组件,用setState()方法更新状态。

// App.js
import React from 'react'; export default class App extends React.Component {
constructor(props) {
super(props); this.state = {
count: 0,
};
} render() {
return (
<div>
<h2>Count: {this.state.count}</h2>
<button onClick={() => this.setState({count: this.state.count + 1})}>
Increment
</button>
</div>
);
}
}

请注意,在较新的代码库中,函数组件比类更常被使用。

它们也更方便,因为我们不必考虑this关键字,并使我们能够使用内置和自定义钩子。

React报错之React hook 'useState' cannot be called in a class component的更多相关文章

  1. React报错之React hook 'useState' is called conditionally

    正文从这开始~ 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditiona ...

  2. React报错之Invalid hook call

    正文从这开始~ 总览 导致"Invalid hook call. Hooks can only be called inside the body of a function compone ...

  3. React报错之react component changing uncontrolled input

    正文从这开始~ 总览 当input的值被初始化为undefined,但后来又变更为一个不同的值时,会产生"A component is changing an uncontrolled in ...

  4. React报错之React Hook useEffect has a missing dependency

    正文从这开始~ 总览 当useEffect钩子使用了一个我们没有包含在其依赖数组中的变量或函数时,会产生"React Hook useEffect has a missing depende ...

  5. React报错之React Hook 'useEffect' is called in function

    正文从这开始~ 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function ...

  6. react 报错的堆栈处理

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

  7. 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 ...

  8. React报错之Expected `onClick` listener to be a function

    正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...

  9. React报错 :browserHistory doesn't exist in react-router

    由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...

随机推荐

  1. VSCode进一步深入了解学习

    紧接上一章节趁热打铁吧,未关注博主的记得关注哦! VSCode设置 (1)关闭预览模式 我们在 VScode 上打开一个新文件的话会覆盖掉以前的文件,这是因为 VSCode 默认开启了预览模式,预览模 ...

  2. Number.prototype.toString()方法

    Number.prototype.toString(radix)方法返回指定基数对应Number的字符串值 radix可选参数,值范围为2~36,转化基数,如果未指定,默认值为10,如果radix值不 ...

  3. Spring基础只是—AOP的概念介绍

    Spring容器包含两个重要的特性:面向切面编程(AOP)和控制反转(IOC).面向切面编程是面向对象(OOP)的一种补充,在面向对象编程的过程中编程针对的目标是一个个对象,而面向切面编程中编程针对的 ...

  4. awk运用三维数组进行插值获得任意经纬度处的水层沉积层地壳厚度

    awk三维数组与插值 目的:给定经纬度,获得该点地下的冰层水层沉积层和地壳的厚度 实现:awk一行命令 下载Crust1.0模型 该数据集的详细介绍见官网. 解压后有几个文件:crust1.vp,cr ...

  5. ruoyi接口权限校验

    此文章属于ruoyi项目实战系列 ruoyi系统在前端主要通过权限字符包含与否来动态显示目录和按钮.为了防止通过http请求绕过权限限制,后端接口也需要进行相关权限设计. @PreAuthorize使 ...

  6. 毕设着急了吧?Python股票数据分析,制作动态柱状图

    写在前面的一些屁话: 雪球成立于 2010 年,是北京雪球信息科技有限公司旗下推出的投资者社区.雪球一直致力于为中国投资者提供跨市场(沪深.香港.美国),跨品种(股票.基金.债券等)的数据查询.资讯获 ...

  7. 『现学现忘』Git后悔药 — 29、版本回退git reset --mixed命令说明

    git reset --mixed commit-id命令:回退到指定版本.(mixed:混合的,即:中等回退.) 该命令不仅修改了分支中HEAD指针的位置,还将暂存区中数据也回退到了指定版本. 但是 ...

  8. 数据孤岛下的新破局 Real Time DaaS:面向 AP+TP 业务的数据平台架构

    从传统数仓,到大数据平台,再到数据中台和湖仓一体新数据平台,在日益加重的数据孤岛困扰下,面向AP场景的解决方案可谓浩如烟海.但实际上,企业在TP类型业务上的投入和AP的比率却高达9:1,为什么没有为T ...

  9. springboot2+jpa+oracle实例

     pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="ht ...

  10. centos更改mac

    centos 6更改mac vim /etc/udev/rules.d/70-persistent-net.rules