如何在嵌套路由中获取 parent 参数?
How to get parent parameter in nested route?
我有以下嵌套的基本结构 routes/components 用于反应应用程序:
/users
->
UsersList
/users/:id
->
UserLayout
/users/:id/
->
UserProfile
/users/:id/settings
->
UserSettings
/users/:id/blah
->
YetAnotherComponent
我想弄清楚的是,在 react router v4 的上下文中,如何访问 UserSettings
组件中的 :id
参数。我可以在 UserLayout
组件中很好地访问它,但在下游的其他任何地方都无法访问它。
我的主要路由器定义位于 Home
组件中,但是所有 user-specific 路由都包含相同的 header 信息,所以我希望所有 user-specific 路由都是嵌套。我当前的结构在 UserLayout
组件中定义了这些嵌套路由。但是,无论我对布局组件的路由定义做什么,除了 "index" 路由 (UserProfile
) 之外,我无法获得任何其他路由来呈现。当尝试访问 UserSettings
或任何其他路由时,我的顶级 404 路由反而被命中。
这是相关的 JSX(实际组件的 render
函数的片段):
主页
<main>
<Switch>
<Route exact path="/login" component={Login} />
<Route exact path="/users" component={UsersList} />
<Route exact path="/users/:id" component={UserLayout} />
<Route exact path="/" component={Home} />
<Route component={NoMatch} />
</Switch>
</main>
用户布局
<div>
<Switch>
<Route path={`${match.url}/settings`} component={UserSettings} />
<Route path="/users/:id/blah" component={YetAnotherComponent} />
</Switch>
<Route path="/users/:id" component={UserProfile} />
</div>
在 UserLayout
组件中,我尝试了 Switch
中显示的两种路径格式,并尝试将 on/off 完全匹配。我唯一能想到的就是使用 Route
组件的 render
参数来传递 id 参数,但这似乎是错误的。这是我唯一的选择吗?
当然,在我 post 几分钟后,我就想通了。在我的顶级路由配置中,我将 /user/:id
设置为需要 exact 匹配。这意味着当我导航到 /user/:id/anything_else
时,反应路由器根本没有加载 UserLayout
,因此没有机会测试我配置的其余路由。
所以我从我的主页组件更改了这个:
<Route exact path="/users/:id" component={UserLayout} />
...为此:
<Route path="/users/:id" component={UserLayout} />
...现在世界一切都很好。
我有以下嵌套的基本结构 routes/components 用于反应应用程序:
/users
->
UsersList
/users/:id
->
UserLayout
/users/:id/
->
UserProfile
/users/:id/settings
->
UserSettings
/users/:id/blah
->
YetAnotherComponent
我想弄清楚的是,在 react router v4 的上下文中,如何访问 UserSettings
组件中的 :id
参数。我可以在 UserLayout
组件中很好地访问它,但在下游的其他任何地方都无法访问它。
我的主要路由器定义位于 Home
组件中,但是所有 user-specific 路由都包含相同的 header 信息,所以我希望所有 user-specific 路由都是嵌套。我当前的结构在 UserLayout
组件中定义了这些嵌套路由。但是,无论我对布局组件的路由定义做什么,除了 "index" 路由 (UserProfile
) 之外,我无法获得任何其他路由来呈现。当尝试访问 UserSettings
或任何其他路由时,我的顶级 404 路由反而被命中。
这是相关的 JSX(实际组件的 render
函数的片段):
主页
<main>
<Switch>
<Route exact path="/login" component={Login} />
<Route exact path="/users" component={UsersList} />
<Route exact path="/users/:id" component={UserLayout} />
<Route exact path="/" component={Home} />
<Route component={NoMatch} />
</Switch>
</main>
用户布局
<div>
<Switch>
<Route path={`${match.url}/settings`} component={UserSettings} />
<Route path="/users/:id/blah" component={YetAnotherComponent} />
</Switch>
<Route path="/users/:id" component={UserProfile} />
</div>
在 UserLayout
组件中,我尝试了 Switch
中显示的两种路径格式,并尝试将 on/off 完全匹配。我唯一能想到的就是使用 Route
组件的 render
参数来传递 id 参数,但这似乎是错误的。这是我唯一的选择吗?
当然,在我 post 几分钟后,我就想通了。在我的顶级路由配置中,我将 /user/:id
设置为需要 exact 匹配。这意味着当我导航到 /user/:id/anything_else
时,反应路由器根本没有加载 UserLayout
,因此没有机会测试我配置的其余路由。
所以我从我的主页组件更改了这个:
<Route exact path="/users/:id" component={UserLayout} />
...为此:
<Route path="/users/:id" component={UserLayout} />
...现在世界一切都很好。