nextjs 使用 Link 组件重新加载页面

mat*_*twg 6 next.js next.js13

我有一个简单的nextjs 13应用程序 ( appDir ),有 2 个页面和一个<Link/>组件导航。

  • 第一页Home- 静态
  • 第二页Test- 在服务器端从第三方源接收动态随机内容(获取)。

问题:当应用程序呈现时,一切正常,但是当我尝试在页面之间切换时,我的测试页面显示旧内容,我可以刷新浏览器以获取实际数据,与通过常规链接导航非常相似,但是<a/>我无需重新加载整个应用程序。

Q:使用组件切换页面时如何强制nextjs 13重新加载页面?Test<Link/>

// src/components/navbar.tsx

'use client'

import {usePathname} from "next/navigation";
import Link from "next/link";

const navItems = [
    {text: 'Home', href: '/'},
    {text: 'Test', href: '/test'}
];

const Navbar = () => {
    const pathname = usePathname();

    return <nav className="nav nav-masthead justify-content-center float-md-end">
        {navItems.map((item: { text: string, href: string, link?: boolean }, idx: number) => (
                <Link key={idx} href={item.href} className={`nav-link${item.href === pathname ? ' active' : ''}`}>
                    {item.text}
                </Link>
            )
        )}
    </nav>
}

export default Navbar;
Run Code Online (Sandbox Code Playgroud)
// src/app/test/page.tsx

import * as crypto from "crypto";

const getData = async () => {
    const res = await fetch('http://localhost:3000/random-data', {cache: 'no-store'});
    if (!res.ok) {
        throw new Error('Failed to fetch data');
    }
    return res.json();
}

export default async function Page() {
    return <p>{crypto.createHash('sha256').update(JSON.stringify(await getData())).digest('hex')}</p>
};

Run Code Online (Sandbox Code Playgroud)

小智 4

我最近在 github 上的反馈讨论中询问了同一主题:https://github.com/vercel/next.js/discussions/41745 ?sort=new#discussioncomment-4620262

问题的原因是Link仅进行客户端导航,并且似乎提供先前访问的组件的缓存状态。您会注意到客户端永远不会回调服务器,因此服务器组件永远不会第二次运行。

我已经搜索了好几天,但还没有找到一种方法来强制重新Link加载或强制刷新组件以重新渲染。

我的结论是,如果您有需要定期刷新的动态数据,最好将其呈现在客户端组件中,而暂时不要使用服务器组件。

此外,如果您想使用 Suspense,则需要使用 SWR 或 React Query 等库来获取任何客户端数据。