开发者问题收集

使用 React Router 后出现错误

2022-05-04
5579

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

错误代码:

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$1 (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;
2个回答

问题

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;
Drew Reese
2022-05-05

编辑:

我认为,您需要的只是用 &lt; 替换 &lt; browserrouter&gt; 。您可能必须添加 &lt; switch&gt;

026068236
rymanso
2022-05-04