没有useReffect Hook条件调用时发生反应错误

时间:2019-06-13 14:29:13

标签: javascript reactjs react-hooks

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 个答案:

答案 0 :(得分:0)