React Hook ‘useState’ 被有条件地调用错误
React Hook ‘useState’ is called conditionally error
“React hook ‘useState’ is called conditionally”错误发生在我们useState
有条件地使用钩子或者在可能返回值的条件之后。要解决该错误,请将所有 React 挂钩移到任何可能返回值的条件之上。
下面是错误如何发生的示例。
应用程序.js
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
可能返回值的条件之后使用第二个钩子。
要解决这个错误,我们必须只
在顶层调用 React hooks。
应用程序.js
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 hooks。
这意味着我们不允许在循环、条件或嵌套函数中使用钩子。
我们永远不应该有条件地调用钩子。
应用程序.js
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> ); }
上面的代码片段导致了错误,因为我们
useState
有条件地调用了第二个钩子。
这是不允许的,因为在重新渲染我们的功能组件时,挂钩的数量和挂钩调用的顺序必须相同。
要解决错误,我们必须将
useState
调用移到顶层,而不是有条件地调用钩子。就像
文档中指出的那样:
- 只在顶层调用钩子
- Don’t call hooks inside loops, conditions or nested functions
- Always use hooks at the top level of your React function, before any early
returns - Only call hooks from React function components or from custom hooks.
This helps React preserve the state of hooks between multiple useState
calls.
Conclusion #
The error “React hook ‘useState’ is called conditionally” occurs when we use
the useState
hook conditionally or after a condition that may return a value.
To solve the error, move all React hooks above any conditionals that may return
a value.