You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 14中如何在404页面隐藏全局页脚

Next.js 14中如何在404页面隐藏全局页脚

嘿,我来帮你搞定这个问题!在Next.js 14的App Router里,要在404页面隐藏全局页脚,有几种简单可行的方法,我结合你的代码给你演示:

方法一:利用Next.js请求头判断(推荐)

Next.js在渲染not-found页面时,会自动添加一个x-nextjs-not-found请求头,值为1。我们可以在根布局的服务器组件中通过headers()函数获取这个请求头,直接判断当前是否是404页面,进而控制页脚的显示。

修改你的根布局代码:
首先导入headers工具:

import { headers } from 'next/headers';

然后在布局组件中添加判断逻辑:

export default async function IndexRoute({ children }: { children: React.ReactNode }) {
  const { data: settings } = await loadSettings()
  const gtmID = settings?.gtmID

  // 获取请求头,判断是否为404页面
  const headerList = headers();
  const isNotFoundPage = headerList.get('x-nextjs-not-found') === '1';

  return (
    <>
      <Suspense>
        <Navbar />
      </Suspense>
      <Suspense>{children}</Suspense>
      {/* 只有非404页面才渲染页脚 */}
      {!isNotFoundPage && (
        <Suspense>
          <Footer />
        </Suspense>
      )}
      {draftMode().isEnabled && <VisualEditing />}
      <GoogleAnalytics GA_TRACKING_ID={gtmID!} />
    </>
  )
}

这样修改后,访问404页面时页脚就不会被渲染了,完美解决你遇到的布局先加载的问题。

方法二:给NotFound组件添加标识属性

如果你不想依赖请求头,也可以给你的NotFound组件添加一个静态标识属性,在根布局中检查这个属性来判断页面类型。

首先修改你的not-found.tsx:

const NotFound = () => {
  return (
    // ... 你的404页面原有内容
  )
}

// 添加静态属性,标识这是404页面
NotFound.isNotFoundPage = true;

export default NotFound;

然后修改根布局代码:

import React from 'react';

export default async function IndexRoute({ children }: { children: React.ReactNode }) {
  const { data: settings } = await loadSettings()
  const gtmID = settings?.gtmID

  // 遍历子元素,检查是否有404页面标识
  const isNotFoundPage = React.Children.toArray(children).some(child => 
    React.isValidElement(child) && 
    typeof child.type === 'function' && 
    (child.type as any).isNotFoundPage
  )

  return (
    <>
      <Suspense>
        <Navbar />
      </Suspense>
      <Suspense>{children}</Suspense>
      {!isNotFoundPage && (
        <Suspense>
          <Footer />
        </Suspense>
      )}
      {draftMode().isEnabled && <VisualEditing />}
      <GoogleAnalytics GA_TRACKING_ID={gtmID!} />
    </>
  )
}

这个方法也能达到同样的效果,不过需要额外修改NotFound组件,相对第一种方法稍显繁琐。

备注:内容来源于stack exchange,提问作者Galanthus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 11:33:00