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

Next.js 13.4.19中实现静态Navbar与页面局部重渲染方案咨询

Next.js 13.4.19 + MUI 实现路由跳转时Navbar不重渲染的方案

在Next.js 13.4+的App Router模式下,利用**布局组件(Layout)**就能轻松实现路由跳转时Navbar保持静态、仅内容区域更新的效果,核心思路是把Navbar放在全局根布局中,让所有页面共享这个布局结构。

1. 配置根布局(Root Layout)

在app目录下创建(或修改)layout.jsx/tsx,这是整个应用的顶层布局,Navbar会在这里渲染,且不会随路由跳转重新渲染:

import Navbar from './components/Navbar';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';

// 自定义你的MUI主题(根据实际需求调整)
const theme = createTheme({
  palette: {
    primary: {
      main: '#1976d2',
    },
  },
});

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN">
      <body>
        <ThemeProvider theme={theme}>
          <CssBaseline />
          {/* Navbar 放在这里,全局共享,不会随路由跳转重渲染 */}
          <Navbar />
          {/* 页面内容会在这个区域动态更新 */}
          <main style={{ marginTop: '64px' }}>{children}</main>
        </ThemeProvider>
      </body>
    </html>
  );
}

2. 编写Navbar组件并使用客户端导航

Navbar组件内部必须使用Next.js的next/link实现客户端跳转,避免页面刷新导致Navbar重渲染,结合MUI组件的示例代码:

import Link from 'next/link';
import { AppBar, Toolbar, Button } from '@mui/material';

export default function Navbar() {
  // 可以加这个日志验证:路由跳转时控制台不会打印这条信息,说明未重渲染
  console.log('Navbar 初始化渲染');

  return (
    <AppBar position="fixed">
      <Toolbar>
        <Link href="/" passHref style={{ textDecoration: 'none', color: 'white' }}>
          <Button color="inherit">首页</Button>
        </Link>
        <Link href="/about" passHref style={{ textDecoration: 'none', color: 'white', marginLeft: '1rem' }}>
          <Button color="inherit">关于我们</Button>
        </Link>
        <Link href="/contact" passHref style={{ textDecoration: 'none', color: 'white', marginLeft: '1rem' }}>
          <Button color="inherit">联系我们</Button>
        </Link>
      </Toolbar>
    </AppBar>
  );
}

3. 页面路由配置

将你的页面组件放在app目录下对应路径的page.jsx/tsx中即可,比如:

  • app/page.jsx → 首页路由/
  • app/about/page.jsx → 关于页路由/about
  • app/contact/page.jsx → 联系页路由/contact

这些页面会自动作为children传入根布局,路由跳转时仅页面内容更新,Navbar保持静态。

关键注意事项

  • 必须使用next/link进行导航,不要用原生<a>标签,否则会触发整页刷新,导致Navbar重渲染
  • 根布局是全局共享的,如果需要部分页面使用不同布局,可以创建嵌套布局(比如app/dashboard/layout.jsx),但根布局的Navbar依然会保留
  • 若Navbar包含动态数据(比如用户登录状态),可以用React的use钩子或SWR/React Query做数据缓存,避免不必要的重渲染

内容的提问来源于stack exchange,提问作者Vishwa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:22:09