React 组件中 useEffect 上的无效钩子调用错误

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

我收到此错误:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app"

我很难理解为什么,因为

useEffect
正在我的反应组件中使用

dealHand
非常简单,只需将两个字符串推入
dealerHand
playerHand
中,并在
useEffect
之外工作。我只是想使用
useEffect
,因为没有它,渲染组件时
dealHand
会被调用两次。

import React, { useEffect } from "react";
import { createRoot } from "react-dom/client";
import { useAtom } from "jotai";
import { playerHandAtom, dealerHandAtom } from "./atoms";
import { dealCard, dealHand } from "./helpers/dealer";

const BlackJack = () => {
  const [dealerHand, setDealerHand] = useAtom(dealerHandAtom);
  const [playerHand, setPlayerHand] = useAtom(playerHandAtom);

  useEffect(() => {
    dealHand();
  }, []);

  return (
    <div id="game-container">
      <img id="game-board" alt="Green Blackjack poker table" src={board} />
    </div>
  );
};

我尝试降级我的依赖项,因为它说版本不匹配也可能是问题,但这不起作用,我想将其保留在 React 18 或更高版本,因为我正在使用 createRoot。 这是我当前的依赖项:

"jotai": "^2.8.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.23.0"

谢谢大家

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

我会尝试将两个版本固定为“18.2.0”而不使用 ^ 符号,18.3.1 是最近的版本,可能很快就会有一些补丁

"react": "18.2.0",
"react-dom": "18.2.0",
© www.soinside.com 2019 - 2024. All rights reserved.