当没有这样的条件调用时,useEffect Hook 条件调用的 React 错误

2024-01-11

React 正在抱怨下面的代码,说它useEffect有条件地被调用:

import React, { useEffect } from "react";
import ReactDOM from "react-dom";

function App() {
  const documentCounts = {};
  const invertedIndexes = {};

  for (const term of []) {
    if (!invertedIndexes[term]) continue;
    // The offending code is the loop below
    for (const arr of invertedIndexes[term]) {
      const documentIndex = arr[0];
      if (!documentCounts[documentIndex]) documentCounts[documentIndex] = 1;
      else ++documentCounts[documentIndex];
    }
  }

  useEffect(() => {});

  return (
    <div className="App">
      <h1>Hello World</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

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? react-hooks/rules-of-hooks

但对我来说,似乎没有条件调用useEffect- 循环仅修改局部变量。有谁知道这里的问题是什么?

(无意义的变量是我将原始代码归结为试图查明问题的变量)

沙盒:https://codesandbox.io/s/friend-diffie-z7edc https://codesandbox.io/s/friendly-diffie-z7edc


检查钩子的官方文档:始终在 React 函数的顶层使用 Hooks。 https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当没有这样的条件调用时,useEffect Hook 条件调用的 React 错误 的相关文章

随机推荐