React Router 为 404 页面添加不同的布局

问题描述 投票:0回答:2

这是组件:

function App() {

  const Main = () => {
    return (
      <section className="app_section">
        <div className="navbar_container">
          <Navbar />
        </div>

        <div className="pages_container">
          <Routes>
            <Route path="/" element={<HomePage />} />
            <Route path="dashboard" element={<DashboardPage />} />
            <Route path="about" element={<AboutPage />} />
            <Route path="terms" element={<TermsPage />} />
            <Route path="privacy" element={<PrivacyPage />} />
            <Route path="api" element={<Api />} />
          </Routes>
        </div>
      </section>
    );
  };

  const NotFound = () => {
    return <p>404</p>;
  };

  return (
    <div className="App">
      <Routes>
        <Route path="login" element={<Login />} />
        <Route path="/*" element={<Main />} />
      </Routes>

    </div>
  );
}

如何为 404 Not Found 页面的路由器添加第三个布局我尝试这样做:

  <Routes>
    <Route path="login" element={<Login />} />
    <Route path="/*" element={<Main />} />
    <Route path="*" element={<NotFound />} />
  </Routes>  

但由于

"/*"
点击了所有链接而无法正常工作,我该如何缓解这种情况?

reactjs react-router react-router-dom
2个回答
1
投票

我建议创建一个

MainLayout
包装组件,其中包含您想要的布局容器组件,并为子路由呈现
Outlet
。在
NotFound
outside
路线上渲染 Route
MainLayout

...

const MainLayout = () => ( <section className="app_section"> <div className="navbar_container"> <Navbar /> </div> <div className="pages_container"> <Outlet /> </div> </section> );

...

const Main = () => { return ( <Routes> <Route path="/" element={<MainLayout />}> <Route index element={<HomePage />} /> <Route path="dashboard" element={<DashboardPage />} /> <Route path="about" element={<AboutPage />} /> <Route path="terms" element={<TermsPage />} /> <Route path="privacy" element={<PrivacyPage />} /> <Route path="api" element={<Api />} /> </Route> <Route path="*" element={<NotFound />} /> </Routes> ); };

Edit react-router-add-different-layout-to-404-page


0
投票

function App() { return ( <div className="App"> <Routes> <Route path="login" element={<Login />} /> <Route path="/*" element={<Main />} /> </Routes> </div> ); }

在CodeSandbox中编辑

© www.soinside.com 2019 - 2024. All rights reserved.