首页 > 解决方案 > why the component doesn't load in nested routing (react)

问题描述

Here i want to load the ShowIt component as a nested route but it doesn't work i mean when i click on the link i go to route of that but the ShowIt component (hello world) doesn't load and i really need to solve this problem
please help me

    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;

标签: reactjsreact-router-domnested-routes

解决方案


You should not use <Link> outside a <Router>. So do this:

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

There are few more issues in your code:

  1. Make ShowIt a react component:
const ShowIt = () => <div>Hello world</div>;
  1. Use a /some-route instead of some-route:
<Link to="/news/components">Go to Components</Link>

And, to access id in ShowIt component:

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

推荐阅读