import { useEffect } from "react";
export const Routes = () => {
useEffect(() => {
console.log("red")
}, []);
const a = [{ name: "sathish" }];
const b = [{ name: "pandi" }];
const c = [{ name: "suren" }];
if (false) {
return a;
} else {
return b;
}
};
使用这段代码,我遇到了类似 × Hooks 只能在函数组件体内调用的错误。
最佳答案
看看Rules of Hooks了解它们的限制以及它们的用途。
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders.
与其他答案和评论不同,导入 React 并返回 JSX 不是函数被视为组件的要求。
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
React 组件的最低要求:
返回一个 React element1,它可以是任何可以渲染的内容:数字、字符串、其他元素或其中任何元素的数组。
请注意 bool 值和null
被忽略。严格返回undefined
(或者不返回,这是一样的)将会失败。那么它必须用作组件:
<MyComponent />
或React.createElement(MyComponent)
在渲染阶段内。
您没有使用Routes
作为一个 React 组件,您可以在渲染阶段之外将其作为函数调用。
import Cookies from 'js-cookie';
import { Routes } from 'routes.js'
import { Redirect } from 'react-router-dom';
const routes = Routes(); // <-- Called as a function, not a component
这就是您收到错误的原因。
当您调用useEffect
时在 Routes
内的正确位置函数,因为它不是在 React 的渲染流程中调用,React 会检测它,就像它在函数组件之外一样。
话虽如此,由于您没有解释您要实现的目标,因此我们无法告诉您如何解决它。告诉你用Routes
因为它位于另一个组件内,可能会产生误导。
1。虽然在 React 文档中被称为元素,但在处理 prop-types 时它被称为节点 .
关于javascript - 钩子(Hook)只能在函数组件体内调用。 (fb.me/react-invalid-hook-call),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59569066/