在非反应组件中使用 useState - 没有错误

问题描述 投票:0回答:1

我不确定为什么这段代码有效。有人可以解释一下吗?

文件名:test.tsx

import { useState } from "react";

export const getComponents = () => {
  const hello = [].map(() => {
    const [state] = useState(0);
    return {
      b: "hello",
      d: <div>{state}</div>,
    };
  });
  return hello;
};

getComponents 不是 React.isValidElement。为什么我可以在这个函数中使用 useState ?

Codesandbox 示例:https://codesandbox.io/p/live/7f832aa1-c029-4083-98dd-c0068c502bc5

我希望 eslint 给我一个错误:““react hooks 必须在 React 函数组件或自定义 React hook 函数中调用”。”

javascript reactjs react-hooks jsx
1个回答
0
投票

它有效,因为它没有任何问题。

有条件地调用钩子是错误的,比如

if (props.something) {
   const [state, setState] = useState(0);
}

在这种情况下,您会收到错误消息。 使用适当的 lint 规则在开发时检测这些错误。

必须始终以相同的数量和相同的顺序调用 Hook。

© www.soinside.com 2019 - 2024. All rights reserved.