【问题标题】:Error: Invalid hook call. Hooks can only be called inside of the body错误:无效的挂钩调用。钩子只能在体内调用
【发布时间】:2021-10-23 01:19:45
【问题描述】:

我正在开发一个 react 应用程序,在我安装 react-router-dom 并尝试将其导入我的 App.js 文件之前它工作正常,我收到此错误:

× 错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。这可能是由于以下原因之一:

  1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本 有关如何调试和解决此问题的提示,请参阅 https://reactjs.org/link/invalid-hook-call

我尝试了一些这种变通方法,但没有成功,而且我没有违反 Hooks 的规则,有人可以帮助我。

https://github.com/facebook/react/issues/15315

我的 json 包如下:

{
  "name": "rmdb-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "styled-components": "^5.3.0",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": " react-scripts start", 
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "preinstall": "npx npm-force-resolutions"
    
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "resolutions": {
    "react": "^17.0.2"
  }

}


【问题讨论】:

  • 当我在 Route 组件中使用 render prop 时遇到了同样的问题并在此处设置条件

标签: reactjs react-router react-hooks npm-install


【解决方案1】:

你的 package.json 中没有 react-router-dom。另外,你能分享一下引发错误的代码吗?

【讨论】:

  • 我在终端 npm install --save react-router-dom 上运行这个命令,我得到了这个错误:marielamagallon@Marielas-MacBook-Pro-2 rmdb-react % npm install --save react -router-dom npm 错误!无效版本:^15.4.2 npm ERR!可以在以下位置找到此运行的完整日志:npm ERR! /Users/marielamagallon/.npm/_logs/2021-08-22T15_46_56_595Z-debug.log
  • 检查你的节点版本。下载节点 js 的 LTS 版本。然后 npm cache clean 和 npm install
  • 谢谢,我终于在我的 package-lock.json 文件中发现了错误,我在那里调用了那个版本的节点 ^15.4.2。我改变了,然后我运行 npm cache clean 和 npm install
  • 太棒了!如果答案有帮助,请通过投票来提供帮助
猜你喜欢
  • 1970-01-01
  • 2022-08-14
  • 2021-04-02
  • 1970-01-01
  • 2022-11-27
  • 2023-01-29
  • 2019-11-21
  • 2021-10-31
  • 1970-01-01
相关资源
最近更新 更多