使用动态参数反应路由器 4 和精确路径 [英] React Router 4 and exact path with dynamic param
问题描述
我在每条路径上都显示组件时遇到问题,因为 React Router 4 没有使用该路径的精确值(或者看起来如此).
I have issues with component being displayed on every single path because React Router 4 isn't using exact for that route (or so it appears).
<Route path="/" exact component={Explore} />
<Route path="/about" component={About} />
// The one making problems
<Route
path="/:username"
exact={true}
render={props => <Profile {...props} />}
/>
因此,当我转到 http://example.com/about 时,我的 Profile 组件仍在呈现.我猜问题出在路由中,因为它期望参数 :username
并且在 /
(root) 之后就出现了.难道我做错了什么?我可以为 /:username
添加另一条路由,例如 /profile/:username
,但如果可能的话,我想保持原样.>
So when I go to http://example.com/about, my Profile component is still being rendered. I guess the problem is in the route as it expects param :username
and that goes right after /
(root). Am I doing something wrong? I could add another route for /:username
, like /profile/:username
, but I'd like to keep it the way it is, if it's possible.
推荐答案
假设您没有使用 Switch.Switch 将解决您的问题,因为它只会呈现匹配的第一个路径.
Assuming that you are not using Switch. Switch will solve your problem because it will only render the first path that matches.
<Switch>
<Route path="/about" component={About}/>
<Route path="/:username" render={props => <Profile {...props} />} />
<Route path="/" component={Explore} />
<Route component={NotFoundPage} />
</Switch>
这篇关于使用动态参数反应路由器 4 和精确路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!