反应路由器 - 不匹配多个路径(v4)

react router - don't match multiple paths (v4)

我有以下 react-router 配置

import React from 'react'
import { BrowserRouter, Route } from 'react-router-dom'

<BrowserRouter>
  <Route exact path='/sign-in' component={SignIn} />
  <Route exact path='/:username' component={Profile} />
</BrowserRouter>

当在像 /dylan 这样的个人资料页面上时,个人资料组件匹配并且 :username 参数是 "dylan",就像我期望的那样。

当导航到 /sign-in 路由时,组件被渲染,组件也被渲染(使用 sign-in 作为用户名)

使用 react-router v4 防止路由匹配多个组件的惯用解决方案是什么?

版本:

@Battle_Slug 是对的。区分路线 /sign-in/user/:username

其实更好

但是如果你真的需要,你可以这样做

function CheckInitialParam(props) {
  if (props.match.params.intialParam === 'sign-in') {
     return <SignIn />
  } else {
     return <Profile />
  }
}
<BrowserRouter>
    <Route path="/:intialParam" component={CheckInitialParam} />
</BrowserRouter>

使用<Switch>也对。

import React from 'react'
import { Switch, Route } from 'react-router-dom'

<BrowserRouter>
  <Switch>
    <Route exact path='/' component={Home} />
    <Route path='/sign-in' component={SignIn} />
    <Route path='/:username' component={Profile} />
  </Switch>
</BrowserRouter>

参考:https://reacttraining.com/react-router/web/api/Switch