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

IT技术 javascript reactjs react-hooks
2021-05-01 00:37:17

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

1个回答

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