使用动态参数反应路由器4和确切路径

Mer*_*isL 2 reactjs react-router react-router-v4 react-router-dom

我在每条路径上都显示组件有问题,因为React Router 4没有对该路由使用确切的路径(或因此出现)。

<Route path="/" exact component={Explore} />
<Route path="/about" component={About} />

// The one making problems
<Route
    path="/:username"
    exact={true}
    render={props => <Profile {...props} />}
/>
Run Code Online (Sandbox Code Playgroud)

因此,当我转到http://example.com/about时,我的Profile组件仍在呈现中。我猜问题出在路由中,因为它期望参数,:username并且在/(root)之后就出现了。难道我做错了什么?我可以为添加一条其他路线/:username,例如/profile/:username,但如果可能的话,我希望保持原样。

Ang*_*zar 6

假设您没有使用Switch。Switch将解决您的问题,因为它只会呈现匹配的第一个路径。

<Switch>
  <Route path="/about" component={About}/>
  <Route path="/:username" render={props => <Profile {...props} />} />
  <Route path="/" component={Explore} />
  <Route component={NotFoundPage} />
</Switch>
Run Code Online (Sandbox Code Playgroud)