React Router 4 and exact path with dynamic param

泄露秘密 提交于 2021-02-08 14:55:40

问题


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} />}
/>

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.


回答1:


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>


来源:https://stackoverflow.com/questions/54986386/react-router-4-and-exact-path-with-dynamic-param

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!