反应路由器两个URL参数&more

时间:2020-10-12 13:06:27

标签: reactjs react-router react-router-dom react-router-v4

我正在使用react-router-dom,这是目前的样子:

<Switch>
        <Route path={"/layouts/:layoutID"} component={Layouts} />
        <Route
          path={"/dashboard/:dashboardID"}
          component={Dashboards}
        />
</Switch>

当用户导航到该组件内的“ / dashboard /:dashboardID”时,他可以选择一个子页面onClick,并且我希望URL结构为“ / dashboard /:dashboardID /:pageID” pageID将导航至“ PageIdComponent”,此组件将获得“匹配”道具,并显示pageID

请参阅显示必要结构的附件。

实现它的最佳方法是什么?enter image description here

1 个答案:

答案 0 :(得分:0)

如果您的子路由位于仪表板组件中,则可以使用match.path值来建立子路由:

<Route path={`${props.match.path}/:dashboardId`}>} component={SubDashboard} />

为了使路径与父级的路径匹配,然后在其上添加一个新变量。

然后,您可以使用match.url导航到它,以链接到当前URL并将子页面添加到其中:

<Link to={`${props.match.url}/pageFour`}>Page four</Link>

React Router可以通过withRouter HOC或各种hooks来为您所需的任何组件提供相关道具,而不是道具钻探。挂钩是在5.1版中引入的

要通过挂钩获得比赛,您可以使用const match = useRouteMatch()

要通过HOC获得相关道具:

const Example = useRouteMatch(function Example({ match, location, history }) {
  return <div>{match.url}</div>;
});

对于React Router v6(即将推出):

https://reacttraining.com/blog/react-router-v6-pre/#nested-routes-and-layouts

相关问题