总览
当我们有条件地使用useState
钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditionally"错误。为了解决该错误,将所有React钩子移到任何可能油返回值的条件之上。
react-hook-usestate-called-conditionally.png
这里有个例子用来展示错误是如何发生的。
代码语言:javascript复制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钩子[3]。
代码语言:javascript复制import React, {useState} from 'react';
export default function App() {
const [count, setCount] = useState(0);
//