Next.js+TypeScript中如何正确展示博客创建日期?
问题解决方案
1. 修复拼写错误
第一个报错的直接原因是属性名拼写错误:把createdEt改成接口定义里的createdAt即可解决Cannot read properties of undefined报错。
2. 解决Date类型无法渲染的问题
React无法直接渲染Date对象(TypeScript会提示Type 'Date' is not assignable to type 'ReactNode'),必须将其转换为字符串类型,同时要注意接口定义与实际后端返回数据的匹配:
情况1:后端返回的是Date对象(少见)
如果接口定义的createdAt: Date和实际数据一致,直接调用日期格式化方法:
{blog.createdAt.toLocaleString()} // 也可自定义格式,比如只显示中文日期 {blog.createdAt.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })}
情况2:后端返回的是ISO日期字符串(常见)
大部分后端接口会返回字符串格式的日期(比如"2024-05-20T10:30:00Z"),此时需要先修正接口定义,再转换为Date对象后格式化:
// 修正接口定义 interface IBlogs { _id?: number name: string; title: string; blog: string; createdAt: string; // 将类型改为string } // 渲染时转换并格式化 {new Date(blog.createdAt).toLocaleString()}
3. 增加容错处理
为避免createdAt不存在或无效的情况,添加可选链和空值合并操作符:
// 针对Date对象的场景 {blog.createdAt?.toLocaleString() ?? '未知日期'} // 针对字符串的场景 {blog.createdAt ? new Date(blog.createdAt).toLocaleString() : '未知日期'}
内容的提问来源于stack exchange,提问作者Misterh100
相关产品推荐
相关产品推荐

