更改路径时反应路由器 dom 不工作

react router dom not working when changing the path

我正在尝试在 React 中使用路由器,但在更改路径时我什么也没得到,您可以在此处查看代码 Link .................. ...............

import React from "react";
import Layout from "./Layout";
import Home from "./Home";
import About from "./About";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

function App() {
  return (
    <Layout>
      <Router>
        <Routes>
          <Route exact path="/" element={<Home />} />
          <Route path="/About" element={<About />} />
        </Routes>
      </Router>
    </Layout>
  );
}

export default App;

import React from "react";
import { BrowserRouter as Router, Link } from "react-router-dom";

function Layout({ children }) {
  return (
    <div>
      <Router>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </Router>
      <div>{children}</div>
    </div>
  );
}

export default Layout;

问题是,您的应用程序中有两个不同的路由器。

您需要在 App.js 中将布局组件移动到您的 Router 组件中

然后删除Layout里面的第二个router。

更多信息在这里:

您需要从路由包装中删除 Router

从“反应”导入反应;从“./Layout”导入布局;从“./Home”导入主页;从“./关于”导入关于; import { BrowserRouter as Routes, Route } from "react-router-dom";

函数 App() { return (

<Routes>
  <Route exact path="/" element={<Home />} />
  <Route path="/About" element={<About />} />
</Routes>
); }

导出默认应用;

<div>{children}</div> 放在 <Router> 中,然后在 app.js 中删除 Router。因为已经在 <Layout>

中声明了

Layout.js

import React from "react";
import { BrowserRouter as Router, Link } from "react-router-dom";

function Layout({ children }) {
  return (
    <div>
      <Router>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>

        <div>{children}</div>
      </Router>
    </div>
  );
}

export default Layout;

App.js

import React from "react";
import Layout from "./Layout";
import Home from "./Home";
import About from "./About";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

function App() {
  return (
    <Layout>
        <Routes>
          <Route exact path="/" element={<Home />} />
          <Route path="/About" element={<About />} />
        </Routes>
    </Layout>
  );
}

export default App;

您当前的代码将输出以下内容:

<div>
  <Router>
    <Link to="/">Home</Link>
    <Link to="/about">About</Link>
  </Router>

  {/* Children (App.js) */}
   <Router>
    <Routes>
      <Route exact path="/" element={<Home />} />
      <Route path="/About" element={<About />} />
    </Routes>
  </Router>
 {/* Children (App.js) */}
</div>

您不需要 <Router>.

的两个实例

这应该是这样的:

  <Router>
    <Link to="/">Home</Link>
    <Link to="/about">About</Link>
    
    {/* Children (App.js) */}
     <Routes>
      <Route exact path="/" element={<Home />} />
      <Route path="/About" element={<About />} />
    </Routes>
    {/* Children (App.js) */}
  </Router>