日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

解決React?hook?'useState'?cannot?be?called?in?a?class?component報錯_React

作者:Borislav?Hadzhiev ? 更新時間: 2022-12-29 編程語言

總覽

當我們嘗試在類組件中使用useState 鉤子時,會產(chǎn)生"React hook 'useState' cannot be called in a class component"錯誤。為了解決該錯誤,請將類組件轉(zhuǎn)換為函數(shù)組件。因為鉤子不能在類組件中使用。

這里有個例子用來展示錯誤是如何發(fā)生的。

// 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>
    );
  }
}

導(dǎo)致這個錯誤的原因是,鉤子只能在函數(shù)組件或自定義鉤子中使用,而我們正試圖在一個類中使用鉤子。

函數(shù)組件

解決該錯誤的一種方法是,將類組件轉(zhuǎn)換為函數(shù)組件。

// 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函數(shù)組件或自定義鉤子中調(diào)用Hook
  • 只在最頂層使用 Hook
  • 不要在循環(huán),條件或嵌套函數(shù)中調(diào)用 Hook
  • 確保總是在你的 React 函數(shù)的最頂層以及任何 return 之前使用 Hook

類組件中使用setState()

另外,我們可以使用一個類組件,用setState()方法更新狀態(tài)。

// 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>
    );
  }
}

請注意,在較新的代碼庫中,函數(shù)組件比類更常被使用。

它們也更方便,因為我們不必考慮this關(guān)鍵字,并使我們能夠使用內(nèi)置和自定義鉤子。

翻譯原文鏈接:bobbyhadz.com/blog/react-…

原文鏈接:https://juejin.cn/post/7135077641073197093

欄目分類
最近更新