开发者问题收集

React Router V6 未捕获错误:您无法在另一个 <Router> 内呈现 <Router>

2022-10-24
267

我目前有如下应用,其中路由包装在 BrowserRouter 中,我收到

Uncaught Error: You cannot render a <Router> inside another <Router>

下面是我的 codesandbox

我做了一个

ctl + F + Shift

并且我的应用中只有 1 个路由器。有人看到语法错误或有建议吗? Codesandbox

这是我的应用程序组件:

import { BrowserRouter, Routes, Route, Router, Link } from "react-router-dom";
import Header from "./components/Header/Header";
import Features from "./components/body/Features/FeaturesGrid/FeaturesGrid";
import Artists from "./components/body/Artists/Artists";
import Fans from "./components/body/Fans/Fans";
import Groups from "./components/body/Groups/Groups";
import Footer from "./components/body/Footer/Footer";
import PPV from "./components/body/PPV/PPV";

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Header />
      </nav>
      <Routes>
        <Route path="/" element={<App />} />
        <Route path="/features" element={<Features />} />
        <Route path="/artists" element={<Artists />} />
        <Route path="/fans" element={<Fans />} />
        <Route path="/groups" element={<Groups />} />
        <Route path="/ppv" element={<PPV />} />
        {/* <Route path="/feed" element={<Feed />} /> */}
      </Routes>
    </BrowserRouter>
  );
}

export default App;

这是我的 Header 组件:

import { useState } from "react";
import HeaderCSS from "../Header/Header.module.css";
import Menu from "../../svgs/bars-solid.svg";
import Close from "../../svgs/times-solid.svg";
import Logo from "../../svgs/logotrans.svg";
import { Link } from "react-router-dom";

function Header() {
  const [menu, setMenu] = useState(false);

  const toggleMenu = () => {
    setMenu(!menu);
  };

  const styleMenu = {
    left: menu ? 0 : "-100%",
  };

  return (
    <header>
      <div className={HeaderCSS.menu} onClick={toggleMenu}>
        <img src={Menu} alt="" width="30" />
      </div>

      <div className="logo">
        <img src={Logo} all="" width="120" height="90" />
      </div>
      <div className={HeaderCSS.nav_container}>
        <ul style={styleMenu}>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/features">Features</Link>
          </li>
          <li>
            <Link to="/artists">Artists</Link>
          </li>
          <li>
            <Link to="/fans">Fans</Link>/
          </li>
          <li>
            <Link to="/groups">Groups</Link>
          </li>
          <li>
            <Link to="/ppv">PPV</Link>
          </li>
          <li>
            <Link to="/feed">Feed</Link>
          </li>
          <li onClick={toggleMenu}>
            <img src={Close} alt="" width="30" className="menu" />
          </li>
        </ul>
      </div>
    </header>
  );
}

export default Header;
1个回答

您正在以递归方式渲染 App

<Route path="/" element={<App />} />

您不能这样做

App 替换为另一个组件

<Route path="/" element={<div />} />
Konrad
2022-10-24