TypeError: history is undefined

TypeError: history is undefined

当我使用history.push函数时,它总是returns这个错误

类型错误:历史未定义

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


function App() {
  let history = useHistory();

  function testing() {
    history.push("/whatever");
  }
  return (
    <div className="App">
      <button onClick={testing}>Test</button>
    </div>
  );
}

export default App;

我的包裹:

{
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.1",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },

最后,我遇到的错误是:

Error

我假设 App 是 index.js 之后的第一个组件,那么您需要将它包裹在 <BrowserRouter> 周围才能使用 useHistory()

在你的根(索引)组件中有这样的东西:

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

import App from "./App";

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