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

Next.js 14中导航至/profile时loading.tsx无法显示的解决方法

Next.js 14 中 /profile 路由自定义 Loading 组件不显示的解决配置

核心前提(App Router,Next.js 14 默认)

Next.js 14 基于 App Router 的加载组件遵循文件系统路由+特殊命名规则,以下是必配步骤:


1. 严格匹配 Loading 组件的命名与位置

必须将自定义加载组件命名为 loading.tsx(或 .jsx),并放在 /app/profile 目录下,与 page.tsx 同级:

app/
└── profile/
    ├── loading.tsx  # 必须在此位置,命名严格
    ├── page.tsx
    └── [可选] layout.tsx

这个命名规则是 Next.js 识别路由级加载组件的核心,放错位置或改名字都不会触发。

2. 确保页面组件是异步且存在等待逻辑

只有当 page.tsx 是异步组件且包含异步操作(如数据请求)时,Next.js 才会触发 loading 状态:

// app/profile/page.tsx
async function ProfilePage() {
  // 模拟异步数据请求(真实场景替换为接口请求)
  const userData = await fetch('/api/user-profile', { 
    cache: 'no-store' // 禁用缓存,确保每次导航都触发加载
  }).then(res => res.json());

  return <div>用户信息:{userData.nickname}</div>;
}

export default ProfilePage;

如果页面是同步组件(无 await 操作),页面会瞬间渲染,loading 组件没有展示机会。

3. Loading 组件的正确写法

loading.tsx 只需返回一个 React 组件,Next.js 会自动将其标记为客户端组件(无需手动加 'use client'):

// app/profile/loading.tsx
export default function ProfileLoading() {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
      <div style={{ width: '40px', height: '40px', border: '4px solid #f3f3f3', borderTop: '4px solid #3498db', borderRadius: '50%', animation: 'spin 1s linear infinite' }}></div>
    </div>
  );
}

4. 排查常见坑点

  • 不要用原生 a 标签导航:必须使用 Next.js 的 next/link 组件进行客户端导航,原生 a 标签会刷新页面,跳过客户端路由的 loading 逻辑。
  • 静态生成页面不会触发 loading:如果你的 /profile 页面启用了静态生成(如使用 generateStaticParams),页面会在构建时生成,导航时直接加载静态文件,不会触发 loading。此时可在 fetch 中添加 cache: 'no-store' 或 revalidate: 0 强制转为动态页面。
  • 全局 loading 与路由级 loading 的区别:如果把 loading.tsx 放在 app/ 根目录,那是全局加载组件,只会在首次应用加载或跨路由段导航时触发,不是 /profile 专属的。

如果你仍在使用 Pages Router(Next.js 14 兼容)

Pages Router 没有自动识别 loading 组件的规则,需手动实现:

  1. 在 _app.tsx 中添加全局 loading 状态,监听路由变化。
  2. 在 /pages/profile.tsx 中通过 getServerSideProps 模拟异步延迟,配合组件内的 loading 状态展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:38:34