【问题标题】:How to render multiple components same route path with React-router如何使用 React-router 渲染多个组件相同的路由路径
【发布时间】:2020-03-11 12:59:09
【问题描述】:

我正在创建一个仪表板页面,如果路由路径是 /dashboard,我总是希望在其中显示一个侧边栏组件。但我也希望 /dashboard 也渲染另一个组件。

我想要达到的目标:

  • 路由路径:/dashboard 应该呈现Sidebar.js + Overview.js 组件。
  • 路由路径:/dashboard/account 应该呈现Sidebar.js + Account.js 组件。
  • 路由路径:/dashboard/favorites 应该呈现Sidebar.js + Favorites.js 组件。
  • 等等……

有人可以指出正确的方向如何实现这一目标吗?我无法理解它......

请参阅下文以更了解我想要的效果:

这是我迄今为止尝试过的:

              <Route path="/" exact component={Home} />
              <Route path="/podcast/:podId/:podName" component={Podcast} />
              <Route exact path="/categori/:categoryName" component={Category} />
              <AuthRoute path="/login" component={Login} />
              <AuthRoute path="/signup" component={Signup} />
            </Switch>
            <Route
              path="/dashboard"
              render={({ match: { url } }) => (
                <>
                  <Route path={`${url}/`} component={Sidebar} />
                  <Route path={`${url}/`} component={Overview} />
                  <Route path={`${url}/favorites`} component={Favorites} />
                </>
              )}
            />```

【问题讨论】:

    标签: reactjs react-router-v4


    【解决方案1】:

    你应该去作曲。创建将组件组合在一起的页面组件并将页面添加到路由器。

    例如FavoritePage.js 将是

    <div>
      <Sidebar />
      <Favorites>
    </div>
    

    其他页面也是如此

    然后在路由器中你将拥有

    <Route path={`${url}/`} component={OverviewPage} />
    <Route path={`${url}/favorites`} component={FavoritesPage} />
    

    或者,如果您希望侧边栏是静态的。参考https://reacttraining.com/react-router/web/guides/quick-start

       <Router>
          <div>
            <Sidebar />
            {/* A <Switch> looks through its children <Route>s and
                renders the first one that matches the current URL. */}
            <Switch>
              <Route path="/overview">
                <Overview />
              </Route>
              <Route path="/overview">
                <Favorites />
              </Route>
              <Route path="/">
                <Overview />
              </Route>
            </Switch>
          </div>
        </Router>
    

    【讨论】:

    • 这不是我要找的。这每次都会重新渲染侧边栏组件。
    • 更新了答案,提供了将侧边栏移出的替代方法
    • 更新的答案并不能解决我的问题。使用您的解决方案侧边栏将呈现在路径上:“/”。我希望它在“/dashboard”上呈现...
    猜你喜欢
    • 2019-08-02
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多