【问题标题】:react router v6 and nest UI and URL反应路由器 v6 并嵌套 UI 和 URL
【发布时间】:2022-07-30 17:12:45
【问题描述】:

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

<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,那么渲染的用户界面将是

<Dashboard >
  <DashboardMessages />
<Dashboard />

/tasks/about 的逻辑相同。

我的理解正确吗?

【问题讨论】:

    标签: reactjs react-native react-hooks react-router react-router-dom


    【解决方案1】:

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

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

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

    当 URL 路径为 "/messages""/tasks" 时,Dashboard 组件将被渲染以及专门匹配的路由内容 DashboardMessagesDashboardTasksOutlet 组件中由Dashboard渲染。

    请注意,"/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>
    

    【讨论】:

      猜你喜欢
      • 2016-08-18
      • 2019-02-18
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多