【发布时间】: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