前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React报错之React hook useState cannot be called in class component

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

作者头像
chuckQu
发布2022-09-20 11:36:56
2K0
发布2022-09-20 11:36:56
举报
文章被收录于专栏:前端F2E

总览

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

react-hook-usestate-cannot-be-called-in-class.png

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

代码语言:javascript
复制
// 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>
    );
  }
}

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

函数组件

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

代码语言:javascript
复制
// 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()方法更新状态。

代码语言:javascript
复制
// 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关键字,并使我们能够使用内置和自定义钩子。

参考资料

[1]

https://bobbyhadz.com/blog/react-hook-usestate-cannot-be-called-in-class-component: https://bobbyhadz.com/blog/react-hook-usestate-cannot-be-called-in-class-component

[2]

Borislav Hadzhiev: https://bobbyhadz.com/about

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-08-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端F2E 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 总览
  • 函数组件
  • 类组件中使用setState()
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档