注释从这开始~

总览

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

这里有个例子用来展现谬误是如何产生的。

// App.jsimport {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.jsimport {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.jsimport 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关键字,并使咱们可能应用内置和自定义钩子。