React Hook ‘useEffect’ is called conditionally 错误

错误“React hook ‘useEffect’ is called conditionally”发生在我们有条件地使用 useEffect hook或者在一个可能返回值的条件之后。 要解决该错误,请将所有 React 挂钩移到任何可能返回值的条件之上。

下面是发生上述错误的示例代码。

import React, {useEffect, useState} from 'react';

export default function App() {
  const [count, setCount] = useState(0);

  if (count > 0) {
    // ⛔️ React Hook "useEffect" is called conditionally.
    // React Hooks must be called in the exact same order in every component render.
    useEffect(() => {
      console.log('count is greater than 0');
    }, [count]);
  }

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

React Hook 'useEffect' is called conditionally 错误

代码示例中的问题是我们有条件地调用 useEffect 钩子。

要解决这个错误,我们必须只在顶层调用 React hooks,这样我们就可以将条件移到 useEffect 钩子中。

import React, {useEffect, useState} from 'react';

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // 👇️ move condition in hook
    if (count > 0) {
      console.log('count is greater than 0');
    }
  }, [count]);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

将 if 语句移到 useEffect 钩子中会有所帮助,因为钩子现在位于顶层并且具有可预测的行为,允许 React 正确地保留 useState 和 useEffect 调用之间的状态。

错误的另一个原因是当我们在可能返回值的条件之后调用 useEffect 钩子时。

import React, {useEffect, useState} from 'react';

export default function App() {
  const [count, setCount] = useState(0);

  // 👇️ might return before useEffect is called
  if (count > 0) {
    return <h1>Count is greater than 0</h1>;
  }

  // ⛔️ React Hook "useEffect" 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?
  useEffect(() => {
    console.log('count is greater than 0');
  }, [count]);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

这里的问题是 useEffect 钩子是在可能返回值的条件之后调用的。

为了解决这个错误,我们必须将所有的钩子调用移到可以返回的条件之上。

import React, {useEffect, useState} from 'react';

export default function App() {
  const [count, setCount] = useState(0);

  // 👇️ moved hook above condition that may return
  useEffect(() => {
    console.log('count is greater than 0');
  }, [count]);

  // 👇️ condition that may return is 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>
  );
}

我们将 useEffect 钩子移到了可能返回值的条件之上。

这意味着我们不允许在循环、条件或嵌套函数中使用钩子。

如文档所述:

  • 只在顶层调用钩子
  • 不要在循环、条件或嵌套函数中调用钩子
  • 在任何早期返回之前,始终在 React 函数的顶层使用钩子
  • 仅从 React 函数组件或自定义钩子调用钩子。

这有助于 React 保留多个 useState 和 useEffect 调用之间的钩子状态。