反应,反应路由器的使用历史。未捕获的错误:无效的挂钩调用

时间:2020-06-02 16:53:02

标签: reactjs react-router react-hooks

我只有一个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"
},

1 个答案:

答案 0 :(得分:0)

解决了, 在webpack.config.js中添加了以下内容:

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

我使用create-react-app,所以我必须运行npm run exit,这是不推荐的。有人对未来有更好的看法吗?