React hook 'useState' is called conditionally報錯解決
總覽
當(dāng)我們有條件地使用useState鉤子時,或者在一個可能有返回值的條件之后,會產(chǎn)生"React hook 'useState' is called conditionally"錯誤。為了解決該錯誤,將所有React鉤子移到任何可能油返回值的條件之上。

這里有個例子用來展示錯誤是如何發(fā)生的。
import React, {useState} from 'react';
export default function App() {
const [count, setCount] = useState(0);
if (count > 0) {
return <h1>Count is greater than 0</h1>;
}
// ?? React Hook "useState" is called conditionally.
//React Hooks must be called in the exact same order
// in every component render. Did you accidentally call
// a React Hook after an early return?
const [message, setMessage] = useState('');
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
上述代碼片段的問題在于,我們使用的第二個useState鉤子,位于可能有返回值的條件之后。
頂層調(diào)用
為了解決該問題,我們必須在最頂層調(diào)用React鉤子。
import React, {useState} from 'react';
export default function App() {
const [count, setCount] = useState(0);
// ??? move hooks above condition that might return
const [message, setMessage] = useState('');
// ??? any conditions that might return must be below all hooks
if (count > 0) {
return <h1>Count is greater than 0</h1>;
}
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
我們把第二個useState鉤子移到了可能返回值的條件之上。
這樣就解決了這個錯誤,因為我們必須確保每次組件渲染時,React鉤子都以相同的順序被調(diào)用。
這意味著我們不允許在循環(huán)、條件或嵌套函數(shù)內(nèi)使用鉤子。
我們絕不應(yīng)該有條件地調(diào)用鉤子。
import React, {useState} from 'react';
export default function App() {
const [count, setCount] = useState(0);
if (count === 0) {
// ?? React Hook "useState" is called conditionally.
// React Hooks must be called in the exact same order in every component render.
const [message, setMessage] = useState('');
}
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
上面的代碼片段導(dǎo)致了錯誤,因為我們有條件地調(diào)用第二個useState鉤子。
這是不允許的,因為鉤子的數(shù)量和鉤子調(diào)用的順序,在我們的函數(shù)組件的重新渲染中必須是相同的。
為了解決這個錯誤,我們必須把useState的調(diào)用移到頂層,而不是有條件地調(diào)用這個鉤子。
就像文檔中所說的:
- 只在最頂層使用 Hook
- 不要在循環(huán),條件或嵌套函數(shù)中調(diào)用 Hook
- 確??偸窃谀愕?React 函數(shù)的最頂層以及任何 return 之前使用 Hook
- 在 React 的函數(shù)組件中調(diào)用 Hook
- 在自定義 Hook 中調(diào)用其他 Hook
原文鏈接:bobbyhadz.com/blog/react-…
以上就是React hook 'useState' is called conditionally報錯解決的詳細內(nèi)容,更多關(guān)于React報錯useState conditionally的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
React Native 使用Fetch發(fā)送網(wǎng)絡(luò)請求的示例代碼
本篇文章主要介紹了React Native 使用Fetch發(fā)送網(wǎng)絡(luò)請求的示例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
react?Table準(zhǔn)備Spin?Empty?ConfigProvider組件實現(xiàn)
這篇文章主要為大家介紹了react?Table準(zhǔn)備Spin、Empty、ConfigProvider組件實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪<BR>2023-02-02
解決react中useState狀態(tài)異步更新的問題
本文主要介紹了react中useState狀態(tài)異步更新的問題,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
React競態(tài)條件Race Condition實例詳解
這篇文章主要為大家介紹了React競態(tài)條件Race Condition實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11

