使用react router后报错

Getting an error after using react router

我是新手。我正在开发我的 React 项目。我的反应组件工作正常。当我安装 React 路由器并在 app.js 中使用它时,我遇到了一些错误,我的网页变成了空白!但是当我从 app.js 页面中删除反应路由器时,我的网页工作正常。我不明白为什么会这样。错误代码如下。如果有人有解决方案,将会有所帮助。

错误代码:

react-dom.development.js:26874 Uncaught Error: useHref() may be used only in the context of a <Router> component.
    at invariant (router.ts:5:1)
    at useHref (hooks.tsx:32:1)
    at LinkWithRef (index.tsx:267:1)
    at renderWithHooks (react-dom.development.js:16175:1)
    at updateForwardRef (react-dom.development.js:20023:1)
    at beginWork (react-dom.development.js:22465:1)
    at beginWork (react-dom.development.js:27381:1)
    at performUnitOfWork (react-dom.development.js:26513:1)
    at workLoopSync (react-dom.development.js:26422:1)
    at renderRootSync (react-dom.development.js:26390:1)

这是我的代码:

import './App.css';
import Home from './components/pages/Home/Home/Home';
import Header from './components/shared/Header/Header';
import { Route, Routes } from 'react-router-dom';
import Inventory from './components/pages/Inventory/Inventory';

function App() {
  return (
    <div className="App">
      <Header></Header>
      <Routes>
        <Route path='/' element={<Home></Home>}></Route>
        <Route path='/home' element={<Home></Home>}></Route>
        <Route path='/inventory' element={<Inventory></Inventory>}></Route>
      </Routes>
    </div>
  );
}

export default App;

编辑:

我认为您只需将 <Routes> 替换为 <BrowserRouter>。您可能还需要添加 <Switch>

import { BrowserRouter, Switch, Route } from "react-router-dom";

      <BrowserRouter>
        <Switch>
        <Route path='/' element={<Home></Home>}></Route>
        <Route path='/home' element={<Home></Home>}></Route>
        <Route path='/inventory' element={<Inventory></Inventory>}></Route>
        </Switch>
      </BrowserRouter>

问题

Uncaught Error: useHref() may be used only in the context of a <Router> component.

此错误通知您您正试图在路由器提供的任何路由上下文之外使用某些react-router-dom功能。换句话说,您的应用程序似乎缺少任何路由器组件来为其呈现的各种 LinkRoutesRoute 组件提供路由上下文。

解决方案

在路由器中呈现应用程序代码。

示例:

import './App.css';
import Home from './components/pages/Home/Home/Home';
import Header from './components/shared/Header/Header';
import {
  BrowserRouter as Router, // <-- (1) import router
  Route,
  Routes
} from 'react-router-dom';
import Inventory from './components/pages/Inventory/Inventory';

function App() {
  return (
    <div className="App">
      <Router> // <-- (2) render router around app code
        <Header />
        <Routes>
          <Route path='/' element={<Home />} />
          <Route path='/home' element={<Home />} />
          <Route path='/inventory' element={<Inventory />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;