Outlet

react-router-dom 中,<Outlet> 是一個特殊的組件,用於在嵌套路由(nested routes)中顯示子路由的內容。它通常與 <Routes><Route> 組件一起使用,用於渲染父路由組件中定義的子路由。

有點類似 nextJS的Layout 可以指定某些路由群組的全局內容和樣式

import { Routes, Route, Outlet } from 'react-router-dom';

const ParentComponent = () => {
  return (
    <div>
      <h2>Parent Component</h2>
      <Outlet /> {/* 這裡會渲染子路由的內容 */}
    </div>
  );
};

const ChildComponent1 = () => {
  return <h3>Child Component 1</h3>;
};

const ChildComponent2 = () => {
  return <h3>Child Component 2</h3>;
};

const App = () => {
  return (
    <Routes>
      <Route path="/" element={<ParentComponent />}>
        <Route path="child1" element={<ChildComponent1 />} />
        <Route path="child2" element={<ChildComponent2 />} />
      </Route>
    </Routes>
  );
};

Browser Router ,Routes ,Route

routes.js

const routes = [
  {
    index: true,
    element: <HomePage />,
    state: 'home',
  },
  {
    path: '/person/:personId',
    index: true,
    element: <PersonDetail />,
    state: 'person.detail',
  },
  {
    path: '/search',
    index: true,
    element: <MediaSearch />,
    state: 'search',
  },
  {
    path: '/password-update',
    element: (
      <ProtectedPage>
        <PasswordUpdate />
      </ProtectedPage>
    ),
    state: 'password.update',
  },
  {
    path: 'password-update',
    element: (
      <ProtectedPage>
        <FavoriteList />
      </ProtectedPage>
    ),
    state: 'favorites',
  },
  {
    path: '/reviews',
    element: (
      <ProtectedPage>
        <ReviewList />
      </ProtectedPage>
    ),
    state: 'reviews',
  },
  {
    path: '/:mediaType',
    element: <MediaList />,
  },
  {
    path: '/:mediaType/:mediaId',
    element: <MediaDetail />,
  },
]
<BrowserRouter>
	<Routes>
		<Route path="/" element={<MainLayout />}>
			{routes.map((route, index) =>
			route.index ? (
			<Route
				index
				key={index}
				element={route.state ? <PageWrapper state={route.state}>{route.element}</PageWrapper> : route.element}
				/>
				) : (
			<Route
				path={route.path}
				key={index}
				element={route.state ? <PageWrapper state={route.state}>{route.element}</PageWrapper> : route.element}
				/>
				)
				)}
		</Route>
	</Routes>
</BrowserRouter>

這段程式碼利用 react-router-dom 中的 <BrowserRouter><Routes><Route> 來設置和渲染應用程序中的路由配置。它動態地根據 routes 陣列來生成路由,並且使用 <MainLayout> 作為整個應用的主要佈局框架,同時使用 <PageWrapper> 來提供額外的包裝和功能。