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

NextJS中重新验证路径后如何路由并刷新页面

解决Next.js数据更新后无法自动展示最新状态的问题

问题分析

你的代码中window.location.reload()会在router.push()完成页面跳转前执行,导致刷新的还是当前页面而非目标页面,因此无法看到更新后的数据。而且在Next.js App Router中,结合revalidatePath的使用,完全不需要手动调用页面刷新,就能实现获取最新数据的需求。

解决方案

1. 修正更新后的跳转逻辑

移除多余的window.location.reload(),确保路由跳转和路径验证的顺序正确:

const path = `/app/homeworks/${res.slug}`;
// 标记目标路径需要重新验证,清除该路径的缓存
await revalidatePath(path);
// 跳转到目标页面,此时页面会自动加载最新数据
await router.push(path);

2. 确保页面能获取最新数据

你需要保证page.tsx中的getData函数能获取到最新数据,有两种可选方式:

方式一:修改fetch的缓存策略

在fetch请求中添加cache: 'no-cache',强制每次请求都从服务器获取最新数据:

async function getData(id: string) {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/homework/${id}`, {
    cache: 'no-cache'
  });

  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }

  return (await res.json()) as Homework;
}
方式二:设置页面的重新验证配置

在page.tsx顶部导出revalidate属性,指定页面的重新验证规则(0表示每次请求都重新验证):

// 配置页面每次请求都重新获取数据
export const revalidate = 0;

async function getData(id: string) {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/homework/${id}`);

  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }

  return (await res.json()) as Homework;
}

原理说明

revalidatePath()会通知Next.js清除指定路径的缓存,当你通过router.push()跳转到该路径时,Next.js会重新执行page.tsx中的getData函数,从接口拉取最新数据并渲染页面,整个过程不需要手动刷新浏览器,就能自动展示更新后的状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:43:15