Next.js V13:在 router.push 后重新验证不触发

Tom*_*Fan 9 javascript typescript reactjs server-side-rendering next.js

我正在使用 Next.js版本 13 应用程序路由,并且在 router.push 调用后无法触发重新验证功能。

在我的项目中,我允许用户在 /blog/create 页面上创建博客文章。如果帖子成功添加到数据库,我将使用 router.push 导航到 /blog 页面。

但是,导航后,似乎 /blog 页面仍在使用旧数据,并且重新验证未触发以获取更新的数据。

因此,新帖子不会显示。

我尝试将 /blog 页面的 revalidate 设置为 0 以确保通过服务器端渲染获取数据,但它似乎不起作用。

目前,我只能通过硬刷新 /blog 页面或单击导航栏按钮再次导航到 /blog 页面来查看新博客文章。

有没有办法在 router.push 调用后强制重新验证触发或解决此问题?任何帮助将不胜感激。谢谢你!

/blog,page.tsx :

export const revalidate = 0;
//export const fetchCache = "no-cache";

async function getData() {
  const postsDocRef = collection(firestore, "posts");
  const q = query(postsDocRef, orderBy("createdAt", "desc"), limit(10));
  const data = await getPosts(q);

  return data;
}

const Blogs = async (): Promise<JSX.Element> => {
  const posts = await getData();

  return <BlogContainer posts={posts} />;
};

export default Blogs;
Run Code Online (Sandbox Code Playgroud)

创建帖子:

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const {
      content,
    } = formik.values;

    const success = await createPost(
     content
    ); //createPost is a function to create new post with try catch block, finally return true if no error
    if (success) {
      router.push("/blogs");
    }
  };
Run Code Online (Sandbox Code Playgroud)

小智 8

目前,我找到的解决方案是使用router.refresh&useTransition钩子的组合:

import { useRouter } from 'next/navigation';
import { useTransition } from 'react'

const Page = () => {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  const onSubmit = () => {
    const url = '/blogs'

    startTransition(() => router.push(url));
    startTransition(() => router.refresh());
  }

  if (isPending) {
    return (
      <div>Loading...</div>
    )
  }

  return // Component
}
Run Code Online (Sandbox Code Playgroud)

来源:Next.js 问题