Eson Wong's Blog

Eson Wong's Blog

马上订阅 Eson Wong's Blog RSS 更新: https://blog.esonwong.com/atom.xml

Next.js 中的日期属性问题

2023年4月10日 21:19

在 Next.js 的 React 组件 props 中,日期类型应当被存储为字符串,而不是日期对象。这是因为 Next.js 的 getStaticPropsgetServerSideProps 函数要求返回的数据必须是 JSON 可序列化的,而日期对象无法直接序列化为 JSON。

转换日期对象

为了在 Next.js 的 props 中使用日期类型,你可以将日期对象转换为字符串。在 JavaScript 中,可以使用 toISOString() 方法将日期对象转换为 ISO 8601 格式的字符串。这样,日期数据就可以被 Next.js 处理,并在组件中使用。

维基百科:国际标准 ISO 8601,是国际标准化组织的日期和时间的表示方法.

例如,在 getStaticProps 中将日期对象转换为字符串:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export async function getStaticProps() {
const res = await fetch("https://.../posts");
const posts = await res.json();

return {
props: {
posts: posts.map((post) =>...

剩余内容已隐藏

查看完整文章以阅读更多