为什么组件不加载嵌套路由(反应)

why the component doesn't load in nested routing (react)

这里我想将 ShowIt 组件作为嵌套路径加载,但它不起作用'加载,我真的需要解决这个问题
请帮助我

    import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from 'react-router-dom';

const ShowIt = <div>Hello world</div>;

const Links = (
  <div>
    <Link to="news/components">Go to Components</Link>
    <br/>
    <Link to="news/states-vs-props">Go to states vs props</Link>
  </div>
);

const News = () => {
  return (
    <div>
      {
        Links
      }
      <Router>
        <Switch>
          <Route path="news/:id">
            <ShowIt />
          </Route>
        </Switch>
      </Router>
    </div>
  );
};

export default News;

你不应该在 <Router> 之外使用 <Link>。所以这样做:

<Router>
  {Links}
  <Switch>
    <Route path="/news/:id">
      <ShowIt />
    </Route>
  </Switch>
</Router>

您的代码中还有几个问题:

  1. 使 ShowIt 成为反应组件:
const ShowIt = () => <div>Hello world</div>;
  1. 使用 /some-route 代替 some-route:
<Link to="/news/components">Go to Components</Link>

并且,要访问 ShowIt 组件中的 id

import { useParams } from "react-router-dom";
// ...
const { id } = useParams<{ id: string }>();