繁体   English   中英

反应路由器 v6 和嵌套 UI 和 URL

[英]react router v6 and nest UI and URL

我试图弄清楚这段代码的含义:

<Routes>
  <Route path="/" element={<Dashboard />}>
    <Route
      path="messages"
      element={<DashboardMessages />}
    />
    <Route path="tasks" element={<DashboardTasks />} />
  </Route>
  <Route path="about" element={<AboutPage />} />
</Routes>

https://reactrouter.com/docs/en/v6/components/route

如果位置是/ ,那么渲染的 UI 将是

<Dashboard />

而如果位置是/messages ,那么渲染的 UI 将是

<Dashboard >
  <DashboardMessages />
<Dashboard />

/tasks/about的逻辑相同。

我的理解正确吗?

你的理解是部分正确的。 给定以下路由代码:

<Routes>
  <Route path="/" element={<Dashboard />}>
    <Route path="messages" element={<DashboardMessages />} />
    <Route path="tasks" element={<DashboardTasks />} />
  </Route>
  <Route path="about" element={<AboutPage />} />
</Routes>

正确的是,当 URL 路径为"/"时,仅呈现Dashboard组件。 这就是所谓的布局路线 布局路由通常提供一些通用组件生命周期和/或通用 UI 布局,即页眉和页脚、导航栏、侧边栏等。

当 URL 路径为"/messages""/tasks"时, Dashboard组件以及专门匹配的路由内容DashboardMessagesDashboardTasks被呈现到由Dashboard呈现的Outlet组件中。

请注意, "/about"路线位于"/"仪表板布局路线之外。 当路径为"/about"时,呈现AboutPage

这是一个示例布局路由组件:

import { Outlet } from 'react-router-dom';

const AppLayout = () => {
  ... common logic ...

  return (
    <>
      <Header />
      <Outlet /> // <-- nested routes render element here
      <Footer />
    </>
  );
};

const NavbarLayout = () => (
  <>
    <Navbar />
    <Outlet /> // <-- nested routes render element here
  </>
);

...

<Routes>
  <Route element={<AppLayout />}>
    ... routes w/ header/footer & w/o navbar

    <Route element={<NavbarLayout />}>
      ... routes also w/ navbar
    </Route>

    ...
  </Route>

  ... routes w/o header/footer
</Routes>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM