TypeError: t.useContext(...) is null 错误在react router Link (React + Webpack)中

TF *_*zen 4 javascript reactjs webpack react-router-dom

我有一个react + django + webpack的项目。我在我的上定义了路线App.js

<NavBar />
<Router>
  <Routes>
    <Route exact path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</Router>
Run Code Online (Sandbox Code Playgroud)

Links我在我的组件中定义NavBar.js

import React from "react";
import { Link } from "react-router-dom";

export default function NavBar() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
  );
}
Run Code Online (Sandbox Code Playgroud)

如果我Link在其中使用App.js它可以正常工作,但是当我在组件中使用它时NavBar.js我会收到此错误:

在此输入图像描述

网络包配置:

<NavBar />
<Router>
  <Routes>
    <Route exact path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</Router>
Run Code Online (Sandbox Code Playgroud)

Switch也尝试使用,但它只能使用超链接<a>

Dre*_*ese 10

您正在组件提供的路由上下文之外渲染Link组件。进入路由上下文。RouterNavBar

<Router> // <-- provides routing context
  <NavBar /> // <-- inside routing context
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</Router>
Run Code Online (Sandbox Code Playgroud)