【问题标题】:React Router add different layout to 404 pageReact Router 为 404 页面添加了不同的布局
【发布时间】:2021-11-24 07:14:10
【问题描述】:

这是组件:

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>  

但由于"/*"点击所有链接而无法正常工作,我该如何缓解?

【问题讨论】:

  • 当你说你想要一个不同的布局时,你指的是Main正在呈现的部分和导航栏吗?你想让NotFound 渲染到不同的布局容器中吗?
  • @DrewReese 是的,为简单起见,我添加了这个const NotFound = () =&gt; { return &lt;p&gt;404&lt;/p&gt;; };
  • 您需要根据您的要求处理您的路线。 /* 太宽泛,应用程序按预期工作。您可能想要更改/*,理想情况下它应该是“特定的”而不是“通用的”

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


【解决方案1】:

我建议创建一个 MainLayout 包装器组件,该组件具有您想要的布局容器组件,并为子路由呈现 Outlet。在Route 上渲染NotFound 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>
  );
};

...

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

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 1970-01-01
    • 2021-12-27
    • 2016-01-18
    • 2016-01-18
    • 2022-11-20
    • 2018-07-11
    • 2020-02-13
    相关资源
    最近更新 更多