• React报错之React hook ‘useState‘ cannot be called in a class component


    🚀 优质资源分享 🚀

    学习路线指引(点击解锁)知识定位人群定位
    🧡 Python实战微信订餐小程序 🧡进阶级本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。
    💛Python量化交易实战💛入门级手把手带你打造一个易扩展、更安全、效率更高的量化交易系统

    正文从这开始~

    总览

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

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-D3Y9dzKn-1661274578536)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/2a01cb9ce10e40568a33eff7e56a4142~tplv-k3u1fbpfcp-watermark.image?)]

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

    // 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 (
          

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

    函数组件

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

    // App.js
    import {useState, useEffect} from 'react';
    
    export default function App() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        console.log('hello world');
      }, []);
    
      return (
        

    Count {count}h2>

    就像文档中所说的那样:

    • 只从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 (
          

    Count: {this.state.count}h2>

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

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

  • 相关阅读:
    Java连接FTP服务器,并使用ftp连接池进行文件操作
    K8S知识点(三)
    Doris的安装和部署(Failed to find 3 backends for policy)
    request和response——请求响应对象
    0087 二叉树
    CSS----字体属性
    王学岗音视频开发(一)—————配置NDK开发环境
    Unity——脚本与序列化
    第2章Linux基础篇-VM和Linux的安装
    软件测试八款优秀的API安全测试工具,会用三款工作效率能提升50%
  • 原文地址:https://blog.csdn.net/m0_56069948/article/details/126495846