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

Next.js中POST请求后调用router.refresh()无法更新页面数据的问题求助

Next.js中POST请求后调用router.refresh()无法更新页面数据的问题求助

我正在开发一个Next.js应用,需要在数据库中创建新的支付记录,之后希望刷新页面来显示更新后的支付列表。我用了router.refresh(),但新数据就是不显示,除非手动刷新整个浏览器。

我的页面路径是app/(user)/user/[userId]/page.tsx,已经设置为动态渲染:

import { Suspense } from "react";
import { UserIdPageWrapper } from "./_components/userId-page-wrapper";

interface UserIdPageProps {
  params: Promise<{ userId: string }>;
}
export const dynamic = "force-dynamic";

export default async function UserIdPage({ params }: UserIdPageProps) {
  const { userId } = await params;

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <UserIdPageWrapper userId={userId} />
    </Suspense>
  );
}

这个页面通过UserIdPageWrapper组件来获取用户和支付数据:

import { db } from "@/lib/db";
import { UserInfo } from "./userInfo";
import { redirect } from "next/navigation";

interface UserIdPageWrapperProps {
  userId: string;
}
export const UserIdPageWrapper = async ({ userId }: UserIdPageWrapperProps) => {
  const [userData, paymentsData] = await Promise.all([
    db.user.findUnique({
      where: {
        id: userId,
      },
    }),

    db.payment.findMany({
      where: {
        userId: userId,
      },
      include: {
        items: true,
      },
    }),
  ]);

  if (!userData || !paymentsData) {
    redirect("/");
  }

  return (
    <UserInfo
      user={userData}
      payments={paymentsData}
    />
  );
};

在客户端组件UserInfo中,我写了一个handleAddPayment函数来发送POST请求创建新支付:

"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import toast from "react-hot-toast";

interface userInfoProps {
  user: User;
  payments: (Payment & { items: PaymentItem[] })[];
}

export const UserInfo = ({ user, payments }: userInfoProps) => {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);

  const handleAddPayment = async () => {
    setIsLoading(true);
    try {
      const res = await fetch("/api/payments", {
        method: "POST",
        body: JSON.stringify({
          userId: user.id,
          totalAmount: 0,
          supervisionRatio: 0,
        }),
        headers: {
          "Content-Type": "application/json",
        },
      });

      if (!res.ok) {
        throw new Error("Failed to add payment");
      }
      const jsonData = await res.json();

      console.log(jsonData);

      toast.success("New payment added");
      router.refresh();
    } catch (error) {
      toast.error("Failed to add payment");
    } finally {
      setIsLoading(false);
    }
  };

  // ... 组件其他部分
};

对应的/api/payments路由处理器代码如下:

import { NextResponse } from "next/server";
import { db } from "@/lib/db";

export async function POST(req: Request) {
  try {
    const { userId, totalAmount, supervisionRatio } = await req.json();
    const res = await db.payment.create({
      data: {
        userId,
        totalAmount,
        supervisionRatio,
        supervisionFee: (totalAmount * supervisionRatio) / 100,
        paymentDate: new Date(),
        remainingAmount: totalAmount - (totalAmount * supervisionRatio) / 100,
      },
    });

    return NextResponse.json(res);
  } catch (error) {
    console.error("[ORDERS_POST]", error);
    return new NextResponse("Internal error", { status: 500 });
  }
}

我已经尝试在page.tsx里设置export const dynamic = "force-dynamic";,但还是没效果。

我试过的操作:

  • 在POST请求后调用router.refresh()
  • 在page.tsx中设置dynamic = "force-dynamic"

我的期望:
创建新支付后,PaymentList组件能自动重新渲染并显示更新后的支付列表,不需要手动刷新整个浏览器。

问题:
我哪里漏掉了?是缓存的问题,还是router.refresh()在这个场景下不是正确的做法?怎么才能确保POST请求后页面能更新显示新数据?

备注:内容来源于stack exchange,提问作者Moaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:18:00