next.js 如何在不获取陈旧数据的情况下对请求进行重复数据消除/缓存?

vwkv1x7d  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(143)

在这个页面上,我需要缓存我的API函数,因为我在Page和generateMetadata函数中需要相同的数据。
由于我使用的是Axios,而不是fetch,因此重复数据删除不会自动发生,我必须将API调用 Package 到React的cache函数中。
问题是,如果我导航到另一个页面,然后返回到这个页面,我接收到的是相同的旧状态数据。我想要的是与getServerSideProps相同的行为,我们总是从服务器加载新的数据。

import * as UsersApi from "@/network/api/users";
import { notFound } from "next/navigation";
import { NotFoundError } from "@/network/http-errors";
import UserProfilePage from "./UserProfilePage";
import { Metadata } from "next";
import { cache } from "react";

interface PageProps {
    params: { username: string; }
};

// TODO: How can I dedupe requests without getting stale data on page navigation?
const getUser = cache(UsersApi.getUserByUsername);

export async function generateMetadata({ params: { username } }: PageProps): Promise<Metadata> {
    try {
        const user = await getUser(username);
        return {
            title: `${user.username} - Flow Blog`,
        };
    } catch (error) {
        if (error instanceof NotFoundError) {
            notFound();
        } else {
            throw error;
        }
    }
}

export default async function Page({ params: { username } }: PageProps) {
    const user = await getUser(username);
    return <UserProfilePage user={user} />;
}
xdnvmnnf

xdnvmnnf1#

您可以在页面组件中导出段配置dynamic,并将其设置为force-dynamic。段级缓存允许您缓存和重新验证路由段中使用的数据。这将在每次请求页面时运行该方法,并使用getServerSideProps复制pages目录中的行为。

import { cache } from 'react';

const getMyData = cache(async () => {
  // fetch your data ..
});

async function MyPage(): Promise<JSX.Element> {
  const response = await getMyData();
  return <></>;
}

export const dynamic = 'force-dynamic';

然后将你的函数 Package 在react的cache函数中,react将自动删除请求的重复数据。
您可以在官方文档中找到有关请求缓存行为的更多信息。

相关问题