【问题标题】:why the component doesn't load in nested routing (react)为什么组件没有在嵌套路由中加载(反应)
【发布时间】:2021-01-25 23:28:32
【问题描述】:

在这里,我想将 ShowIt 组件加载为嵌套路由,但它不起作用我的意思是当我单击链接时,我会转到该路由,但 ShowIt 组件(hello world)没有加载,我真的需要解决这个问题
请帮帮我

    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;

【问题讨论】:

    标签: reactjs react-router-dom nested-routes


    【解决方案1】:

    您不应在&lt;Router&gt; 之外使用&lt;Link&gt;。这样做:

    <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 }>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 2022-12-20
      • 2019-02-18
      • 2019-10-21
      • 2017-07-23
      • 1970-01-01
      相关资源
      最近更新 更多