【问题标题】:Next.js - How to hide navigation and footer component on 404 page?Next.js - 如何在 404 页面上隐藏导航和页脚组件?
【发布时间】:2021-11-14 05:10:57
【问题描述】:
import Footer from "./Footer";
import Navigation from "./Navigation";
import { useRouter } from "next/router";

function Layout({ children }) {
  const router = useRouter();
  return (
    <>
      {router.pathname !== "/*" && <Navigation />}
      {/* {router.pathname !== "*" && <Navigation />} */}
      <main className="main-content">{children}</main>
      {router.pathname !== "/*" && <Footer />}
      {/* {router.pathname !== "*" && <Footer />} */}
    </>
  );
}

export default Layout;

很遗憾,带星号的方法不起作用:/ ?!?

提前谢谢大家,向大家致以最诚挚的问候;-)

【问题讨论】:

  • 如果页面是 404 或 500 路径名总是/_error 所以{router.pathname !== "/_error" &amp;&amp; &lt;Navigation /&gt;}
  • 谢谢尼科 ????????另外一个问题如果我们有自定义 404 错误页面怎么办?我想还有另一条路....????
  • 请看我的回答

标签: next.js http-status-code-404


【解决方案1】:

如果你没有使用自定义404页面,默认router.pathname_error所以

{router.pathname !== "/_error" && <Navigation />}

应该可以。

如果您使用自定义 404 页面(/pages 内的 404.js)router.pathname/404

如果您在页面或组件中重复使用built in error page router.pathnamerouter.pathname 将是当前页面路径。
例如:

import Error from 'next/error'

const MyPage = ({isError = true})=>{
    // pagepath would be something like pages/mypage
    return isError ?  <Error statusCode={"404"} /> : <p>My page </p>
}

export default MyPage 

在这种情况下,上述两种方法都不起作用。
但是我不建议使用这种方法。

【讨论】:

  • 非常感谢尼科! ?? 一切似乎都很完美!最好的问候??
【解决方案2】:

我决定添加此代码以服务遇到相同问题的其他人。就我而言,当我们有 custom 404 page 时,解决方案看起来像这样 =>

import Footer from "./Footer";
import Navigation from "./Navigation";
import { useRouter } from "next/router";

function Layout({ children }) {
  const router = useRouter();
  return (
    <>
      {router.pathname !== "/404" && <Navigation />}
      <main className="main-content">{children}</main>
      {router.pathname !== "/404" && <Footer />}
    </>
  );
}

export default Layout;

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 2021-02-01
    • 2017-01-14
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    相关资源
    最近更新 更多