无法在类组件中调用 React Hook ‘useState’

React Hook ‘useState’ 不能在类组件中调用

React Hook ‘useState’ cannot be called in class component

当我们尝试在类组件中使用钩子时,会出现错误“React hook ‘useState’ cannot be called in a class component” useState

要解决该错误,请将您的类转换为函数,因为不能在类组件中使用钩子。

react hook usestate不能在类中调用

下面是错误如何发生的示例。

应用程序.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> ); } }
错误是因为钩子只能在函数组件或自定义钩子内部使用,而我们试图在类内部使用钩子。

将类转换为函数组件

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

应用程序.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 函数组件或自定义钩子调用钩子。
  • 只在顶层调用钩子
  • 不要在循环、条件或嵌套函数中调用钩子
  • 在任何早期返回之前,始终在 React 函数的顶层使用钩子

setState()或者,在类组件中使用

或者,我们可以使用类组件并使用该方法更新状态
setState()

应用程序.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
并使我们能够使用内置和自定义挂钩。