【问题标题】:Next.js only runs getServerSideProps once, not fetching new data when accessed by next/routerNext.js 只运行一次 getServerSideProps,next/router 访问时不获取新数据
【发布时间】:2021-09-20 21:49:56
【问题描述】:

我有一个带有 SSR 的 Next.js 应用程序,我在其中导出了一个 getServerSideProps 异步函数,如下所示:

export const getServerSideProps = getGenericServerSideProps([""]);

getGenericServerSideProps 是从另一个文件导入的异步函数,该文件调用无头 CMS 以获取数据:

export const getInitialProps = (slices: string[], ...callbacks) => async (
    context: NextPageContext
): Promise<CmsPageResponse> => {
    for (const callback of callbacks) {
        if (Array.isArray(callback)) {
            continue;
        }
        callback();
    }
    const lang = getLangFromContext(context);
    const { slug } = context.query as { slug: string[] };

    const paths = getPaths(slug, lang);

    return await getCmsPageManager([...slices, ...paths].join("/"), lang);
};

export const getGenericServerSideProps = (slices: string[], ...callbacks) => async (
context: NextPageContext
): Promise<any> => {
    const appConfiguration = getAppConfiguration();
    const props = await getInitialProps(slices, callbacks)(context);
    return { props: { ...props, appConfiguration } };
};

如果我通过 URL 访问该页面(例如直接访问 app/page1),它将运行 getServerSideProps 并为我提供新数据。

如果我再次尝试访问同一页面,但通过路由器链接:

<Link href={ROUTES[Pages.Home]} as={ROUTES[Pages.Home]}><a>Link</a></Link>

它不执行 getServerSideProps 并给我旧数据。

如何强制 Next.js 在每次访问页面时执行getServerSideProps?现在,它似乎正在使用构建应用程序时创建的道具(如果我重新构建应用程序,新道具和旧道具会同步,但如果我对 CMS 中的数据进行更改,则页面在第二次渲染时显示旧数据)。

【问题讨论】:

  • getServerSideProps 将在对其所在页面的每个请求中调用。你有什么缓存吗?
  • @juliomalves 我没有任何特定的缓存,但是,我测试了它是否真的在通过路由器(使用控制台日志)进行页面更改时调用getServerSideProps,它似乎没有调用它。它只被调用一次,第一次加载页面,之后就不再进入那个函数了。
  • 你是如何检查getServerSideProps被调用的?您是否正在检查启动 Next.js 服务器的终端以获取日志?

标签: javascript reactjs next.js


【解决方案1】:

留下一个错误的答案,因为我已经弄清楚了。

显然,该项目已在 next.config.js 中为所有请求的所有 json 文件设置了自定义缓存控制标头,但请求的失效时间很长,并且 Next.js 显然将其应用于页面后通过 AJAX 请求的 JSON 文件最初加载 GSSP。

检查您的 next.config.js 人员。

【讨论】:

    猜你喜欢
    • 2023-02-12
    • 2021-09-29
    • 2020-12-13
    • 2021-09-26
    • 1970-01-01
    • 2021-04-21
    • 2021-11-02
    • 2021-12-22
    • 2022-01-23
    相关资源
    最近更新 更多