当没有这样的条件调用时,对 useEffect Hook 条件调用反应错误 [英] React error for useEffect Hook conditional call when there is no such conditional call
问题描述
React 抱怨下面的代码,说它useEffect
被有条件地调用:
import React, { useEffect } from "react";从react-dom"导入 ReactDOM;功能应用(){const documentCounts = {};const reverseIndexes = {};for (const term of []) {如果 (!invertedIndexes[term]) 继续;//有问题的代码是下面的循环for (const arr of reverseIndexes[term]) {const 文档索引 = arr[0];if (!documentCounts[documentIndex]) documentCounts[documentIndex] = 1;否则 ++documentCounts[documentIndex];}}useEffect(() => {});返回 (<div className="应用程序"><h1>你好世界</h1>
);}const rootElement = document.getElementById("root");ReactDOM.render(
React Hook "useEffect" 被有条件地调用.在每个组件渲染中,必须以完全相同的顺序调用 React Hooks.您是否在提前返回后不小心调用了 React Hook?反应钩子/钩子规则
但对我来说似乎没有条件调用 useEffect
- 循环只是修改局部变量.有没有人碰巧知道这里的问题是什么?
(无意义的变量是我将原始代码归结为试图查明问题的原因)
沙盒:https://codesandbox.io/s/friendly-diffie-z7edc
查看有关 hooks 的官方文档:始终在 React 函数的顶层使用 Hook.
React is complaining about code below, saying it useEffect
is being called conditionally:
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
But to me it seems like there is no conditional call to useEffect
- the loop just modifies local variables. Does anyone happen to know what the problem here is?
(the pointless variables are what I boiled down my original code down to to try to pinpoint the issue)
Sandbox: https://codesandbox.io/s/friendly-diffie-z7edc
Check official documentation on the hooks: Always use Hooks at the top level of your React function.
这篇关于当没有这样的条件调用时,对 useEffect Hook 条件调用反应错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!