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



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/friendly-diffie-z7edc

查看有关钩子的官方文档:始终在 React 函数的顶层使用 Hooks。

相关内容

  • 没有找到相关文章