React报错之React hook 'useState' is called conditionally
<p>正文从这开始~</p><h2 id="总览">总览</h2>
<p>当我们有条件地使用<code>useState</code>钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditionally"错误。为了解决该错误,将所有React钩子移到任何可能油返回值的条件之上。</p>
<p><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5913f48a52434aae8246e6eee44123b2~tplv-k3u1fbpfcp-watermark.image?"></p>
<p>这里有个例子用来展示错误是如何发生的。</p>
<pre><code class="language-jsx">import React, {useState} from 'react';
export default function App() {
const = 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 = useState('');
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
</code></pre>
<p>上述代码片段的问题在于,我们使用的第二个<code>useState</code>钩子,位于可能有返回值的条件之后。</p>
<h2 id="顶层调用">顶层调用</h2>
<p>为了解决该问题,我们必须在最顶层调用React钩子。</p>
<pre><code class="language-jsx">import React, {useState} from 'react';
export default function App() {
const = useState(0);
// 👇️ move hooks above condition that might return
const = 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>
);
}
</code></pre>
<p>我们把第二个<code>useState</code>钩子移到了可能返回值的条件之上。</p>
<blockquote>
<p>这样就解决了这个错误,因为我们必须确保每次组件渲染时,React钩子都以相同的顺序被调用。</p>
</blockquote>
<p>这意味着我们不允许在循环、条件或嵌套函数内使用钩子。</p>
<p>我们绝不应该有条件地调用钩子。</p>
<pre><code class="language-jsx">import React, {useState} from 'react';
export default function App() {
const = 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 = useState('');
}
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
</code></pre>
<p>上面的代码片段导致了错误,因为我们有条件地调用第二个<code>useState</code>钩子。</p>
<p>这是不允许的,因为钩子的数量和钩子调用的顺序,在我们的函数组件的重新渲染中必须是相同的。</p>
<blockquote>
<p>为了解决这个错误,我们必须把<code>useState</code>的调用移到顶层,而不是有条件地调用这个钩子。</p>
</blockquote>
<p>就像文档中所说的:</p>
<ul>
<li>只在最顶层使用 Hook</li>
<li>不要在循环,条件或嵌套函数中调用 Hook</li>
<li>确保总是在你的 React 函数的最顶层以及任何 return 之前使用 Hook</li>
<li>在 React 的函数组件中调用 Hook</li>
<li>在自定义 Hook 中调用其他 Hook</li>
</ul><br><br>
来源:https://www.cnblogs.com/chuckQu/p/16611276.html
頁:
[1]