反应路由器 useHistory 上的钩子调用无效

时间:2021-04-28 11:21:57

标签: javascript reactjs

我知道在新版本中对 react 路由器库进行了一些更改,但我认为我正确地遵循了更改并且仍然收到以下错误

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, {useRef} from 'react';
import { useHistory } from 'react-router-dom';
function Home() {
    const history = useHistory(); //This hook causing the error
    const RouteAbout = () => {
      history.push("/about");
    }
    return(<> 
       <button onClick={RouteAbout}> test </button>
    </>);
}

错误是指

const history = useHistory();

从进口

import { useHistory } from 'react-router-dom';

如何以有效的方式将 useHistory 钩子与反应路由器一起应用?

编辑:

App.JS

function App() {
  return (
    <>
    <Router>
        <Header/>
        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/portfolio">
            <Portfolio />
          </Route>
          <Route path="/contact">
            <Contact />
          </Route>
        </Switch>
    </Router>
    <Footer/>
    </>
  );
}

版本

    "history": "^5.0.0",
    "node-sass": "^5.0.0",
    "react": "^16.14.0",
    "react-dom": "^17.0.2",
    "react-perf-devtool": "^3.1.8",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^4.0.3",
    "web-vitals": "^1.0.1"

2 个答案:

答案 0 :(得分:1)

您确定将您的应用程序包装在 BrowserRouter 中吗?

此代码对我有用。

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

function App() {
  let history = useHistory();
  const RouteAbout = () => {
    history.push("/about");
  };
  return (
    <>
      <button onClick={RouteAbout}> test </button>
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
    <BrowserRouter>
    <App />
    </BrowserRouter>,
  rootElement
);

答案 1 :(得分:0)

未找到导致此错误的原因,但找到了替代方法。

使用 NavLink 虽然链接和按钮作为 HTML 标签的冲突对我有用。 一个好的解决方案是删除 <button> 标签并使用 <a> 提供的 NavLink 标签“伪造”标签。

<NavLink to="/about" onClick={() => window.scrollTo(0, 0)}><button>test</button></NavLink>

<NavLink to="/about" onClick={() => window.scrollTo(0, 0)}>test</NavLink>