React从Firestore拉取多条数据时出现渲染错误求助
解决React渲染Firestore Timestamp字段报错问题
你的报错原因很明确:check_in字段是Firestore存储的Timestamp对象(结构为{seconds, nanoseconds}),React不允许直接渲染对象类型的子元素——它只能渲染字符串、数字、React元素这类基本/合法类型。
你之前用map遍历文档数组是正确的,但map只是帮你把文档数据整合到数组里,并没有处理Timestamp这个对象,所以渲染check_in时依然会触发错误。
下面是几种可行的解决方法:
方法1:获取数据时提前转换Timestamp
在提取文档数据的步骤里,把Timestamp转成JavaScript Date对象,后续渲染就可以直接格式化:
const filteredData = data.docs.map((doc) => { const docData = doc.data(); return { ...docData, id: doc.id, // 调用Timestamp的toDate()方法转为Date对象 check_in: docData.check_in.toDate() }; });
渲染时用Date对象的格式化方法:
<h4>Check In: {booking.check_in.toLocaleDateString()}</h4>
方法2:渲染时直接转换
如果不想修改原始数据,也可以在渲染阶段临时处理:
<h4>Check In: {booking.check_in.toDate().toLocaleDateString()}</h4>
方法3:自定义时间格式
需要更个性化的展示格式时,可以用Intl.DateTimeFormat做精细化配置:
<h4>Check In: {new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }).format(booking.check_in.toDate())}</h4>
内容的提问来源于stack exchange,提问作者Denim Behn
相关产品推荐
相关产品推荐

