React报错之React hook 'useState' cannot be called in a class component
正文从这开始~
总览
当我们尝试在类组件中使用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的更多相关文章
- React报错之React hook 'useState' is called conditionally
正文从这开始~ 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditiona ...
- React报错之Invalid hook call
正文从这开始~ 总览 导致"Invalid hook call. Hooks can only be called inside the body of a function compone ...
- React报错之react component changing uncontrolled input
正文从这开始~ 总览 当input的值被初始化为undefined,但后来又变更为一个不同的值时,会产生"A component is changing an uncontrolled in ...
- React报错之React Hook useEffect has a missing dependency
正文从这开始~ 总览 当useEffect钩子使用了一个我们没有包含在其依赖数组中的变量或函数时,会产生"React Hook useEffect has a missing depende ...
- React报错之React Hook 'useEffect' is called in function
正文从这开始~ 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function ...
- react 报错的堆栈处理
react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...
- 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 ...
- React报错之Expected `onClick` listener to be a function
正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...
- React报错 :browserHistory doesn't exist in react-router
由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...
随机推荐
- Ansible Playbook概览
Ansible playbook 执行需要三步路执行: 1.编写playbook 2.定义主机清单文件 3.设置运行环境,写入配置文件 1.编写playbook Playbook使用YAML语法格式进 ...
- 面试官:Redis 过期删除策略和内存淘汰策略有什么区别?
作者:小林coding 计算机八股文网站:https://xiaolincoding.com 大家好,我是小林. Redis 的「内存淘汰策略」和「过期删除策略」,很多小伙伴容易混淆,这两个机制虽然都 ...
- Codeforces Round #802 (Div. 2)
题集链接 A Optimal Path 水 代码 #include <bits/stdc++.h> #define endl "\n" using namespace ...
- nodejs - http.request是否有超时
默认没有.那么,req.setTimeout(msec, callback)是干什么用的. 它的意思是 socket msec 没有活动后执行callback,不帮你关闭连接. 就像一个秒表,每收到数 ...
- HMS Core音频编辑服务支持7种音频特效,助力一站式音频处理
多媒体时代,音频作为内容传播中的重要形式,因其不受空间限制.认知负担小.声音元素多样化等特点,广泛应用于短视频制作.儿童在线教育.有声阅读.游戏等领域产品,在各种形式的音频呈现过程中,合理添加音效能够 ...
- java,捕获和抛出异常
package Exrro; public class Test { //ctrl + alt + T快速生成异常捕捉 public static void main(String[] args) { ...
- Linux shell脚本进阶使用
shell的循环控制语句 - continue:提前结束某次循环,重新开始下一次 - break:提前结束某层循环 范例: #求100以内的奇数和 #!/bin/bash sum=0 for i in ...
- 在 SQL Server 中使用 Try Catch 处理异常
如何在 SQL Server 中使用 Try Catch 处理错误? 从 SQL Server 2005 开始,我们在TRY 和 CATCH块的帮助下提供了结构错误处理机制.使用TRY-CATCH的语 ...
- 【New】Code Insertion
#include <bits/stdc++.h> using namespace std; #define Multicase() for(int T = read() ; T ; T-- ...
- 有一种密码学专用语言叫做ASN.1
目录 简介 ASN.1的例子 ASN.1中的内置类型 ASN.1中的限制语法 总结 简介 ASN.1是一种跨平台的数据序列化的接口描述语言.可能很多人没有听说过ASN.1, 但是相信有过跨平台编程经验 ...