Next.js点击Link组件触发页面刷新而非SPA跳转的原因排查
我的Next.js应用有两个页面:/(首页)和/test,每个页面都用Link组件做了跳转链接。但点击链接时,应用没有像SPA那样只重新渲染目标页面,反而像普通HTML锚点一样刷新整个页面——这会导致我在应用顶层维护的共享状态被重新初始化,麻烦得很。
相关代码如下:
// app/test/page.tsx import { Metadata } from "next/types"; import React from "react"; import { Layout } from "@/components/Layout/Layout" import Link from "next/link"; export const metadata: Metadata = { title: "This is a test page", description: "Next app description", }; export default function Test() { return ( <Layout> <h1>Test Page</h1> <Link href="/">Home Page</Link> </Layout> ); }
// app/page.tsx import styles from "./page.module.css"; import DemoComponent from "../components/DemoComponent/DemoComponent"; import React from "react"; import { Layout } from "@/components/Layout/Layout"; import Link from "next/link"; export const metadata = { title: "Home Page", description: "Next app description", }; export default function Home() { return ( <Layout> <DemoComponent /> Home Page <Link href="/test">Test Page</Link> </Layout> ); }
附开发者工具中的文档请求截图:
检查
Link组件的导入和使用方式
确认你导入的是Next.js官方提供的Link组件(import Link from "next/link"),不是自定义的同名组件或者其他库的Link。另外,别在Link组件里面嵌套原生的<a>标签,不然会触发原生跳转逻辑,直接刷新页面。核对Next.js的路由配置和版本
你的代码是Next.js 13+的App Router结构,默认应该支持客户端导航。但如果next.config.js里设置了output: 'export'(静态导出),会直接禁用客户端路由,导致全页刷新。打开配置文件看看,把不必要的静态导出设置删掉,或者确认路由配置没问题。排查
Layout组件的代码
两个页面都嵌套在Layout里,如果Layout里写了干扰客户端导航的代码——比如手动给元素绑定click事件然后调用window.location.href,或者有阻止Next.js默认导航的逻辑——都会导致页面刷新。去检查下Layout组件的代码,确保没覆盖Link的默认行为。检查浏览器扩展或脚本冲突
有些浏览器扩展(比如广告拦截器、代理工具)可能会干扰Next.js的客户端导航逻辑。试试在无痕模式下打开应用,或者禁用所有扩展,看看是不是恢复正常了。
内容的提问来源于stack exchange,提问作者dulesaga

