React-router-dom:点击 Link 无限期地添加路由到 Url Link

React-router-dom: Clicking on Link adds the route to the Url Link indefinitely

经过多次尝试,我成功地使用 React-router-dom.
实现了基本的嵌套路由 这是简单的项目结构:

这里是相关文件

App.js

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import ParentComponent from "./Components/nestedComponents/ParentComponent";
import NavBar from "./Components/Shared/NavBar";
function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <NavBar />
        <Switch>
          <Route path="/home" name="Home" component={ParentComponent} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

NavBar.js

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

export default function NavBar() {
  return (
    <div>
      <Link to={`home/nestedComponentOne`}> Nested Component One </Link>
      <Link to={`home/nestedComponentTwo`}> Nested Component Two </Link>
    </div>
  );
}

ParentComponent.js

import React from "react";
import nestedComponentOne from "./nestedComponentOne";
import nestedComponentTwo from "./nestedComponentTwo";
import { Switch, Route } from "react-router-dom";

export default function ParentComponent() {
  return (
    <div>
      <Switch>
        <Route path="/home/nestedComponentOne" component={nestedComponentOne} />
        <Route path="/home/nestedComponentTwo" component={nestedComponentTwo} />
      </Switch>
    </div>
  );
}

nestedComponentOne.js

import React from "react";

export default function nestedComponentOne() {
  return <div>NESTED COMPONENT 1</div>;
}

nestedComponentTwo.js

import React from "react";

export default function nestedComponentTwo() {
  return <div>NESTED COMPONENT 2</div>;
}

所以这是 结果:
如果我点击 nestedComponentOne

如果我点击 nestedComponentTwo:

问题 是当我在第一次点击后再次点击 nestedComponentOne(或两个)时,路线被添加到 url 字符串 而不是替换它:

您为什么不尝试将所有路线放在一个文件中。像这样:

<Route exact path="/home" name="Home" component={ParentComponent} />
<Route path="/home/nestedComponentOne" component={nestedComponentOne} />
<Route path="/home/nestedComponentTwo" component={nestedComponentTwo} />

您的代码需要一些更新。 Working Demo

NavBar.js

这里你忘了在link前面加上斜杠/从根。

      <Link to={`/home/nestedComponentOne`}> Nested Component One </Link>
      <Link to={`/home/nestedComponentTwo`}> Nested Component Two </Link>

ParentComponent.js

由于我们从该组件中删除了 Switch,因此我们需要从父路由器获取匹配信息并传递路径以导航相应的嵌套组件

     export default function ParentComponent({ match }) {
      return (
        <div> 
          <Route path={`${match.path}/nestedComponentOne`} component={nestedComponentOne} />
          <Route path={`${match.path}/nestedComponentTwo`} component={nestedComponentTwo} />
        </div>
      );
    }