【问题标题】:React Router nesting反应路由器嵌套
【发布时间】:2020-12-20 14:38:47
【问题描述】:

我正在尝试在反应路由器中使用嵌套路由。但我的嵌套 routig 不起作用。如果那会有所不同,我正在使用 Typescript。

//This is working
<Route exact path={path} component={StudentList}></Route>
//This is not working
<Route path={`${path}/:id`} component={StudentComponent}></Route>

我有一个名为 StudentModule 的模块。在模块 a 中,当我路由到时,有两条类似上面的路由 /students/1 没有渲染

我在 CodeSandbox 上创建了一个示例应用 https://codesandbox.io/s/vibrant-pasteur-n1eq7

要查看问题所在,请导航至菜单中的学生,然后单击学生。它需要渲染 StudentComponent 并在屏幕上写入Student works。

请帮我看看我的代码有什么问题?

【问题讨论】:

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


    【解决方案1】:

    在你的主路由器上,你声明了

      <Route exact path="/students" component={StudentModule} />
    

    因为您从一方面将路径设置为exact,并且没有将路径声明为students*,而导航到students/1,所以您根本没有进入拥有子路由器的Route .

    【讨论】:

      【解决方案2】:

      在组件StudentModule中,请声明变量id,我想你错过了它,字符串文字将id理解为一般字符串。 并传递 url 之类的

      <Route exact path={`${path}/${id}`} component={StudentComponent}></Route>
      

      在下面找到更新的代码:

      import React from "react";
      import { useEffect } from "react";
      import { Route, Switch, useRouteMatch } from "react-router-dom";
      import StudentComponent from "./Student";
      import StudentList from "./StudentList";
      
      export default function StudentModule() {
        let { path } = useRouteMatch();
      let id = 1;
        useEffect(() => {
          console.log(path);
        });
        return (
          <Switch>
            <Route exact path={path} component={StudentList}></Route>
            <Route exact path={`${path}/${id}`} component={StudentComponent}></Route>
          </Switch>
        );
      }
      
      

      试试看,希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2019-02-18
        • 1970-01-01
        • 2016-08-18
        • 1970-01-01
        • 2017-07-23
        • 2017-08-06
        • 1970-01-01
        • 2020-11-19
        • 2019-08-10
        相关资源
        最近更新 更多