解決React?hook?'useState'?cannot?be?called?in?a?class?component報錯
總覽
當我們嘗試在類組件中使用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-…
以上就是解決React hook 'useState' cannot be called in a class component報錯的詳細內(nèi)容,更多關(guān)于React報錯useState component的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
react結(jié)合typescript?封裝組件實例詳解
這篇文章主要為大家介紹了react結(jié)合typescript?封裝組件實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
淺談react-native熱更新react-native-pushy集成遇到的問題
下面小編就為大家?guī)硪黄獪\談react-native熱更新react-native-pushy集成遇到的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
React實現(xiàn)歌詞滾動效果(跟隨音樂播放時間滾動)
這篇文章主要為大家詳細介紹了React實現(xiàn)歌詞滾動效果(跟隨音樂播放使勁按滾動),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2024-02-02
React?antd中setFieldsValu的簡便使用示例代碼
form.setFieldsValue是antd?Form組件中的一個方法,用于動態(tài)設(shè)置表單字段的值,它接受一個對象作為參數(shù),對象的鍵是表單字段的名稱,值是要設(shè)置的字段值,這篇文章主要介紹了React?antd中setFieldsValu的簡便使用,需要的朋友可以參考下2023-08-08

