每个请求在客户端组件上使用 SWR 获取数据。 Next.js 13.3 + SWR

问题描述 投票:0回答:1

带有应用程序目录的 Next.js 13.3。我有一个显示日期的非常简单的组件。他只显示它 1 次,之后它不再更新,直到我重建它。在 Next.js 12 中,它的工作方式有所不同(刷新页面 - 更新数据)。我究竟做错了什么?我不知道如何让它根据每个请求更新日期。

为什么 SWR 不更新每个请求的信息?

api/你好/route.ts


export async function GET(request: Request) {
  // const { searchParams } = new URL(request.url);

  const response = await fetch(
    "https://timeapi.io/api/Time/current/zone?timeZone=Europe/Kiev",
    { cache: "no-cache" }
  );

  const data = await response.json();
  console.log(data);

  return NextResponse.json(data);
}

time.tsx

"use client";

import useSWR from "swr";
import { fetcher } from "~/lib/fetcher";

export const Time = () => {
    const { data, error, isLoading } = useSWR("api/hello", fetcher);

  if (error) {
    return <div>error</div>;
  }

  if (isLoading) return <div>loading...</div>;

  console.log(data);
  return (
    <div>
      <div>{data.dateTime}</div>
    </div>
  );
};

fetcher.ts

export const fetcher = (...args: any) => fetch(...args).then(res => res.json())

page.tsx

import { Inter } from "next/font/google";
import { Time } from "~/components/time";

const inter = Inter({ subsets: ["latin"] });

export const revalidate = 0;

export default async function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <Time />
    </main>
  );
}
javascript reactjs next.js next
1个回答
0
投票

您正在使用的 useSWR 钩子是一个数据获取库,它提供了一种简单有效的方法来处理 React 中的数据获取。默认情况下,useSWR 将缓存从 API 返回的数据,并且仅在缓存中的数据陈旧时才获取新数据。

为确保您的组件根据每个请求进行更新,您可以为“useSWR”挂钩提供一个唯一键,该键会根据每个请求进行更改。这将导致 useSWR 在密钥更改时重新获取数据。

比如可以给key加上时间戳,让它对每个请求都是唯一的:

import useSWR from "swr";
import { fetcher } from "~/lib/fetcher";

export const Time = () => {
  const timestamp = new Date().getTime(); // Get a unique timestamp
  const { data, error, isLoading } = useSWR("api/hello", fetcher, {
        revalidateOnMount: true
    });

  if (error) {
    return <div>error</div>;
  }

  if (isLoading) return <div>loading...</div>;

  console.log(data);
  return (
    <div>
      <div>{data.dateTime}</div>
    </div>
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.