反应路由器 v4。 "exact" 属性是否禁止任何嵌套路由?

React-router v4. Does "exact" prop forbid any nested Route?

我注意到,如果我创建 <Route path={'/'} exact component={Profile} />,我就不能嵌套任何其他内部组件,因为该道具 "exact" 会阻止任何匹配并停止渲染。

我要构建的是一个带有个人资料和订单页面的简单应用程序。每个页面都有自己的侧边栏和一些订单项目列表。我在每个页面内使用嵌套路由来根据当前位置重新排列正确的订单列表。为了使这个应用程序完美,我需要在起始位置呈现个人资料页面(例如,'https://myapp.com')。

我阅读了所有文档,唯一的解决方案是在 Route 组件中使用 "exact" prop。但这是太脆弱的解决方案,因为如果我想使用嵌套路由来定义侧边栏或订单列表。

是否有任何其他方法可以构建可以在“https://myapp.com”位置显示个人资料页面但还允许我使用嵌套路由的路由?

我当前的实现是下一个:

<Switch>
   <Route path={'/'} exact component={Profile} />
   <Route path={'/orders'} component={Orders} />
   <Route component={NotFound} />
</Switch>

class Profile extends Component {
   render() {
      return (
         <div className='profile_page'>
            <Profile_Bar />

            <div className='content'>
               <Switch>
                  <Route path={'/subscribers'} component={User_List} />
                  <Route path={'/dashboard'} component={Dashboard} />
               </Switch>
            </div>
         </div>
      )
   }
}

class Orders extends Component {
   render() {
      return (
         <div className='orders_page'>
            <Orders_Bar />

            <div className='content'>
               <Switch>
                  <Route path={'/active'} component={Orders_List} />
                  <Route path={'/completed'} component={Orders_List} />
               </Switch>
            </div>
         </div>
      )
   }
}

const NotFound = ({ location }) => (
  <div>
    NotFound {location.pathname}
  </div>
)

在我以前的实现中,我使用 <Redirect /> 代替:

<Switch>
   <Redirect from='/' to='/profile'/>
   <Route path={'/profile'} component={Profile} />
   <Route path={'/orders'} component={Orders} />
   <Route component={NotFound} />
</Switch>

理想情况下,您的 Profile 组件将在其自己的路径(如“/profile”)中处理,并创建一个单独的组件,例如 Home ,对于您的“/”路线:

<Switch>
  <Route path={'/'} exact component={Home} />
  <Route path={'/profile'} component={Profile} />
  <Route path={'/orders'} component={Orders} />
  <Route component={NotFound} />
</Switch>

...然后您的 Profile 组件将具有如下子路由:

<Switch>
  <Route path={'/profile/subscribers'} component={User_List} />
  <Route path={'/profile/dashboard'} component={Dashboard} />
</Switch>

如果你真的不想在路由路径中使用 'profile' 那么你可以将 '/subscribers' 和 '/dashboard' 路由添加到你的主要路由,它们都呈现 Profile 组件,但您可能仍想用自己的组件处理 '/' 路由:

<Switch>
  <Route path={'/'} exact component={Home} />
  <Route path={'/subscribers'} component={Profile} />
  <Route path={'/dashboard'} component={Profile} />
  <Route path={'/orders'} component={Orders} />
  <Route component={NotFound} />
</Switch>

我想另一种选择是更改路线的顺序,以便“/orders”匹配在“/”之前。然后,您可以从“/”路由中删除 exact,以便子路由也匹配。

不过,在这种情况下,您必须在 Profile 组件中处理 NotFound 路由,这并不理想。

<Switch>
  <Route path={'/orders'} component={Orders} />
  <Route path={'/'} component={Profile} />
</Switch>