我具有调用函数getMyAge
的以下服务器组件Home
:
// app/page.tsx
import { getMyAge } from './utils/datetime';
export default function Home() {
return (
<Page>
<Paragraph>I'm {getMyAge()} years old</Paragraph>
</Page>
);
}
// app/utils/datetime.ts
export function getMyAge() {
const today = new Date();
const birthDate = new Date(1997, 1, 17);
const yearDifference = today.getFullYear() - birthDate.getFullYear();
const monthDifference = today.getMonth() - birthDate.getMonth();
const dayDifference = today.getDate() - birthDate.getDate();
if (monthDifference < 0 || (monthDifference === 0 && dayDifference < 0)) {
return yearDifference - 1;
} else {
return yearDifference;
}
}
它在开发中运行得很好,但是在我为生产生成静态构建之后,getMyAge的结果没有改变.我看到,由于Side是静态生成的,所以该函数只在构建时运行.当用户请求页面时,如何使其在运行时运行?
谢谢.
通过查看Next Docs,我发现getServerSideProps
可以做到这一点,但使用App Router的示例似乎都涉及到它们在Fetch API上的扩展的重新验证选项,这是我不需要的.有什么方法可以在不求助于客户端组件的情况下实现这一点吗?