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

Next.js 13中revalidateTag期间显示加载模态框的实现问题

解决方案

问题核心在于startTransition的isPending仅跟踪服务器动作中fetch请求的执行阶段,而revalidateTag触发的缓存重验证是后台异步完成的,此时isPending已变为false,导致模态框提前消失。以下是两种可行的实现方案:

方案一:手动维护加载状态 + 监听数据更新

通过自定义isLoading状态控制模态框显示,结合useEffect监听依赖groups标签的数据变化,在重验证完成(数据更新)时关闭模态框。

客户端组件代码:

'use client';

import { useState, useEffect, useTransition } from 'react';
import { deleteSources } from '@/actions';
import LoadingModal from '@/components/LoadingModal';

export default function DeleteButton({ email, selectedChannelIds, groups }) {
  const [isLoading, setIsLoading] = useState(false);
  const [isPending, startTransition] = useTransition();

  const handleDelete = () => {
    setIsLoading(true);
    startTransition(async () => {
      await deleteSources(email, selectedChannelIds);
      // 不立即关闭loading,等待重验证后数据更新
    });
  };

  // 监听groups数据变化,重验证完成后关闭模态框
  useEffect(() => {
    if (groups && isLoading) {
      setIsLoading(false);
    }
  }, [groups, isLoading]);

  return (
    <>
      <button onClick={handleDelete} disabled={isPending || isLoading}>
        删除渠道
      </button>
      {isLoading && <LoadingModal />}
    </>
  );
}

父服务器组件代码:

import DeleteButton from './DeleteButton';

export default async function Page() {
  // 获取依赖groups标签的数据,重验证后会自动更新
  const groups = await fetch('/api/groups', { next: { tags: ['groups'] } }).then(res => res.json());

  return <DeleteButton email="user@example.com" selectedChannelIds={[1,2]} groups={groups} />;
}

方案二:使用SWR的状态跟踪重验证过程

借助SWR的isValidating状态,它会自动跟踪数据的重新获取过程(包括revalidateTag触发的重验证),结合startTransition的isPending实现全程加载状态。

代码示例:

'use client';

import useSWR from 'swr';
import { useTransition } from 'react';
import { deleteSources } from '@/actions';
import LoadingModal from '@/components/LoadingModal';

const fetcher = (url) => fetch(url).then(res => res.json());

export default function DeleteButton({ email, selectedChannelIds }) {
  const { isValidating } = useSWR('/api/groups', fetcher, {
    next: { tags: ['groups'] }
  });
  const [isPending, startTransition] = useTransition();

  const handleDelete = () => {
    startTransition(async () => {
      await deleteSources(email, selectedChannelIds);
    });
  };

  // 合并fetch阶段(isPending)和重验证阶段(isValidating)的状态
  const isLoading = isPending || isValidating;

  return (
    <>
      <button onClick={handleDelete} disabled={isLoading}>
        删除渠道
      </button>
      {isLoading && <LoadingModal />}
    </>
  );
}

原理说明:

  • isPending:跟踪startTransition中服务器动作的fetch执行阶段。
  • isValidating:SWR提供的状态,当数据因revalidateTag触发重新获取时,该状态会变为true,直到新数据加载完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:47:45