Visual Studio React 模板项目 - 错误:无效的挂钩调用

发布于 2025-01-10 17:36:41 字数 1047 浏览 1 评论 0原文

我正在使用 Visual Studio 2022 中的 React Web 应用程序模板来创建一个 Web 项目。

创建项目后,我安装了一个使用钩子实现的组件,例如通过包管理命令的 React-Bootstrap -

npm install react-bootstrap [email protected]

然后我将其导入到 home.js -

import Button from 'react-bootstrap/Button';

并添加一个元素 -

<div>
  <Button variant="primary">Button #1</Button>
  <Button variant="secondary" className="mx-2">Button #2</Button>
  <Button variant="success">Button #3</Button>
</div>

运行项目,我收到以下错误 -

错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。发生这种情况的原因之一可能是: 1. 您的 React 和渲染器版本可能不匹配(例如 React DOM) 2. 您可能违反了 Hooks 规则 3. 您可能在其中拥有多个 React 副本相同的应用程序请参阅 https://reactjs.org/link/invalid-hook-call 了解有关如何调试和解决此问题的提示。

我没有添加任何其他代码,我认为模板中的代码有问题,但我无法找出问题所在。

I am using the React web application template in Visual Studio 2022 to create a web project.

Right after project is created, I installed a component that's implemented with hooks, e.g. React-Bootstrap by package management command -

npm install react-bootstrap [email protected]

Then I import it to home.js -

import Button from 'react-bootstrap/Button';

and add an element -

<div>
  <Button variant="primary">Button #1</Button>
  <Button variant="secondary" className="mx-2">Button #2</Button>
  <Button variant="success">Button #3</Button>
</div>

Run the project and I get the following error -

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 See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

I haven't added any other code and I think there is something wrong with the code in the template but I can't figure out the issue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

∞梦里开花 2025-01-17 17:36:41

看起来模板生成的 React 代码使用的是较旧的 React 16.0,而 home.js 仍然是基于类的组件。

通过命令“npm install react”和“npm install react-dom”(升级到16.14)升级react和react-dom,并将Home.js组件更改为基于函数的组件解决了我的问题。

Looks like the React code generated by the template was using older react 16.0 and the home.js is still a class based component.

Upgrade react and react-dom by command "npm install react" and "npm install react-dom" (upgraded to 16.14) and also change the Home.js component to be a function based component solved my problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文