【问题标题】:React, react-router useHistory. Uncaught Error: Invalid hook call反应,反应路由器使用历史。未捕获的错误:无效的挂钩调用
【发布时间】:2020-09-21 05:27:06
【问题描述】:

我只有一份 React,用 npm ls react 检查过,react 和 react-dom 是同一个版本,我没有违反任何钩子规则,对吧?我不知道该怎么办了。

ERROR: 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

我的组件:

import React from "react";
import { useHistory } from "react-router-dom";

export default function HomeButton() {
    let history = useHistory();

    function handleClick() {
     history.push("/home");
    }

    return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
    );
}

package.json

"dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.19.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1",
    "styled-components": "^5.1.1"
},

【问题讨论】:

  • 你如何渲染HomeButton
  • 在 App.js 中。我运行 npm ls react agian,注意到我得到了以下 └── react@16.12.0。所以我猜那是两个版本,有什么解决方案吗?
  • 现在我从 react docs 运行它并收到 true,这意味着没有两个版本的 react: // 在 node_modules/react-dom/index.js 中添加这个 window.React1 = require( '反应'); // 在你的组件文件中添加这个 require('react-dom'); window.React2 = require('react'); console.log(window.React1 === window.React2);
  • 你确定这是你在应用程序中唯一使用反应钩子的地方吗?

标签: reactjs react-router react-hooks


【解决方案1】:

解决了, 在 webpack.config.js 中添加解决以下问题:

 alias: {
        react: path.resolve("./node_modules/react"),
        }

我使用 create-react-app,所以我不得不运行 npm runeject,不推荐。有人对未来有更好的想法吗?

【讨论】:

  • 我也在使用 create-react-app。我尝试了您的解决方案,但没有成功。
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
相关资源
最近更新 更多