解决React hook 'useState' cannot be called in a class component报错

目录
  • 总览
  • 函数组件
  • 类组件中使用setState()

总览

当我们尝试在类组件中使用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 hook 'useState' cannot be called in a class component报错的详细内容,更多关于React报错useState component的资料请关注我们其它相关文章!

(0)

相关推荐

  • 解决React报错You provided a `checked` prop to a form field

    目录 总览 defaultChecked onChange 初始值 总览 当我们在多选框上设置了checked 属性,却没有onChange 处理函数时,会产生"You provided a checked prop to a form field without an onChange handler"错误.为了解决该错误,可以使用defaultChecked 属性,或者在表单字段上设置onChange 属性. 这里有个例子用来展示错误是如何发生的. // App.js export

  • 解决React报错Rendered more hooks than during the previous render

    目录 总览 顶层调用 条件之上 总览 当我们有条件地调用一个钩子或在所有钩子运行之前提前返回时,会产生"Rendered more hooks than during the previous render"错误.为了解决该错误,将所有的钩子移到函数组件的顶层,以及不要在条件中使用钩子. 这里有个示例用来展示错误是如何发生的. // App.js import {useEffect, useState} from 'react'; export default function App

  • 解决React报错Parameter 'props' implicitly has an 'any' type

    目录 总览 安装类型文件 声明类型 泛型 重新安装 总览 当我们没有为函数组件或者类组件的props声明类型,或忘记为React安装类型声明文件时,会产生"Parameter 'props' implicitly has an 'any' type"错误.为了解决这个错误,在你的组件中明确地为props对象设置一个类型. 安装类型文件 你首先要确定的是你已经安装了React类型声明文件.在项目的根目录下打开终端,并运行以下命令. # ️ with NPM npm install --s

  • 解决React报错React Hook useEffect has a missing dependency

    目录 总览 禁用规则 依赖移入 依赖移出 useMemo useCallback 总览 当useEffect钩子使用了一个我们没有包含在其依赖数组中的变量或函数时,会产生"React Hook useEffect has a missing dependency"警告.为了解决该错误,禁用某一行的eslint规则,或者将变量移动到useEffect钩子内. 这里有个示例用来展示警告是如何发生的. // App.js import React, {useEffect, useState}

  • 解决React报错Invalid hook call

    目录 总览 版本匹配 调用组件 总览 导致"Invalid hook call. Hooks can only be called inside the body of a function component"错误的有多种原因: react和react-dom的版本不匹配. 在一个项目中有多个react包版本. 试图将一个组件作为一个函数来调用,例如,App()而不是<App />. 在类里面使用钩子,或者在不是组件或自定义钩子的函数中使用钩子. 版本匹配 在项目的根目录

  • 解决React报错Cannot find namespace context

    目录 总览 tsx 安装@types/包 手动添加 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig.json文件中把jsx设置为react-jsx,并确保为你的应用程序安装所有必要的@types包. 这里有个例子来展示错误是如何发生的. // App.ts import React from 'react'; interface UserCtx { first: stri

  • 解决React报错Property does not exist on type 'JSX.IntrinsicElements'

    目录 总览 组件大写 类型声明 总结 总览 当组件名称以小写字母开头时,会导致"Property does not exist on type 'JSX.IntrinsicElements'"错误.为了解决该错误,确保组件名称总是以大写字母开头,安装React声明文件并重启你的开发服务器. 这里有个示例用来展示错误是如何发生的. // App.tsx // ️ name starts with lowercase letter function myComponent() { retu

  • 解决React hook 'useState' cannot be called in a class component报错

    目录 总览 函数组件 类组件中使用setState() 总览 当我们尝试在类组件中使用useState 钩子时,会产生"React hook 'useState' cannot be called in a class component"错误.为了解决该错误,请将类组件转换为函数组件.因为钩子不能在类组件中使用. 这里有个例子用来展示错误是如何发生的. // App.js import {useState, useEffect} from 'react'; class Example

  • React hook 'useState' is called conditionally报错解决

    目录 总览 顶层调用 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditionally"错误.为了解决该错误,将所有React钩子移到任何可能油返回值的条件之上. 这里有个例子用来展示错误是如何发生的. import React, {useState} from 'react'; export default function App() { const [count,

  • 解决react中useState状态异步更新的问题

    目录 疑惑 状态异步更新带来的问题 问题示例 问题解决 类组件的解决方案 函数组件的解决方案 其他解决方案 结尾 疑惑 相信刚开始使用react函数组件的小伙伴也遇到过一个坑,就是 useState 更新状态是异步更新的,但是react 并没有提供关于这个问题的解决方案.那我们能否使用自己的方法来解决这个问题呢?答案肯定是可以的. 状态异步更新带来的问题 就拿一个比较常见的场景来说.在react项目中,我们想在关闭对话框后再去处理其他业务.但是 useState 的状态是异步更新的.我们通过se

  • 完美解决python遍历删除字典里值为空的元素报错问题

    exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' } 使用下列遍历的方法删除: 1. for e in exam: 2. if exam[e] == '': 3. del exam[e] 结果出现下列错误,怎么解决: Traceback (most recent call last): File "Untitled.py", line 3, in <module> for e in

  • 解决vue 子组件修改父组件传来的props值报错问题

    vue不推荐直接在子组件中修改父组件传来的props的值,会报错 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "result&

  • 解决vue 使用axios.all()方法发起多个请求控制台报错的问题

    今天在项目中使用axios时发现axios.all() 方法可以执行但是控制台报错,后来在论坛中看到是由于axios.all() 方法并没有挂载到 axios对象上,需要我们手动去添加 == 只需要在你封装的axios文件里加入 == instance.all = axios.all 就完美解决了! 补充知识:vue项目中使用axios.all处理并发请求报_util2.default.axios.all is not a function异常 报错: _util2.default.axios.

  • 解决Laravel5.x的php artisan migrate数据库迁移创建操作报错SQLSTATE[42000]

    Laravel5.x运行迁移命令创建数据表:php artisan migrate报错. Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users` add unique `users_email_uniqu

  • 解决使用stream将list转map时,key重复导致报错的问题

    要将List对象集合转为map集合,可以通过stream流的形式快速实现转换: //三个Users对象组成一个List集合 List<Users> list = new ArrayList<>(); list.add(Users.builder().userName("11").userId(1).build()); list.add(Users.builder().userName("11").userId(2).build()); lis

  • React Hook中useState更新延迟问题及解决

    目录 React Hook中useState更新延迟 React Hook useState连续更新对象问题 React Hook中useState更新延迟 方法一:去掉useEffect的第二个参数 例如以下代码 错误实例 const[zoom, setZoom] = useState(0); useEffect(() = >{     document.getElementById('workspace-content').addEventListener('mousewheel', scr

  • React Hook 'useEffect' is called in function报错解决

    目录 总览 声明组件 声明自定义钩子 总结 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function component nor a custom React Hook function",可以将函数名的第一个字母大写,或者使用use作为函数名的前缀.比如说,useCounter使其成为一个组件或一个自定义钩子. 这里有个示例用来展示错误是如何发生的. // App.j

随机推荐