1

这是问题的简化再现:具有嵌套 URL 的子级不呈现。

我的文件结构基本上是这样的:

-App
 --Home
 --Pageone
  ---Childone

我可以渲染Homeor Pageonefrom App,然后我可以渲染Homeor Pageonefrom Pageoneor Home,但我不能Childone从它的“父页面”渲染Pageone。我不太确定做错了什么。

下面分享代码,还有这个沙箱

应用程序.jsx

import { BrowserRouter, Switch, Route } from "react-router-dom";
import Pageone from "./Pageone";
import Home from "./Home";

export default function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/">
          <Home />
        </Route>
        <Route exact path="/pageone">
          <Pageone />
        </Route>
      </Switch>
    </BrowserRouter>
  );
}

主页.jsx

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

const Home = () => {
  return (
    <div>
      <p>This is HOME!</p>
      <Link to="/pageone">Pageone</Link>
    </div>
  );
};

export default Home;

Pageone.jsx

import { Link, Route, useRouteMatch } from "react-router-dom";
import Childone from "./Childone";

const Pageone = () => {
  const { path, url } = useRouteMatch();
  return (
    <div>
      <Route exact path={path}>
        <PageoneContent url={url} />
      </Route>
      <Route exact path={path + "/childone"}>
        <Childone />
      </Route>
    </div>
  );
};

const PageoneContent = (props) => {
  return (
    <div>
      <p>This is pageone!</p>
      <Link to="/">Go back Home</Link>
      <br />
      <Link to={props.url + "/childone"}>Go to Child One</Link>
    </div>
  );
};

export default Pageone;

Childone.jsx

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

const Childone = () => {
  return (
    <div>
      <p>This is Child one!</p>
      <Link to="/">Go back Home</Link>
    </div>
  );
};

export default Childone;
4

1 回答 1

1

据我所知,您需要使用另一个Switch路由,否则反应将不知道如何匹配该路由路径。

<div>
  <Route exact path={path}>

应该:

<Switch>
  <Route exact path={path}>
于 2021-08-13T10:39:15.983 回答