首页 > 解决方案 > 由于时间戳,当我在 firebase 上添加数据时,null 不是对象

问题描述

我有一些关于 firebase 的文档,每个人都有一个 height 值和一个包含创建时间的 createdAt 值(例如:13/05/2021 上午 1:00:33),但要显示它我需要 toDate()、getDate( ),getMonth() 函数将其转换并使其可打印

<Text style= {styles.text}>{props.item.createdAt.toDate().getDate()+"/"}</Text>
<Text style= {styles.text}>{props.item.createdAt.toDate().getMonth()+1+"/"}</Text>
<Text style= {styles.text}>{props.item.createdAt.toDate().getFullYear()}</Text>
<Text style= {styles.text}>{props.item.height}</Text>

我还有一个在firebase上添加用户高度的功能

export function addHeight(heightMeasure, addComplete){
    firebase
        .firestore()
        .collection("Measures")
        .doc(firebase.auth().currentUser.uid)
        .collection("height")
        .add(heightMeasure)
        .then((snapshot) => {
            heightMeasure.id = snapshot.id
            snapshot.set(heightMeasure)
        })
        .then(() => addComplete(heightMeasure))
        .catch((error) => console.log(error))
}

在哪里

   var heightMeasure = {
            "height" : name,
            "createdAt": firebase.firestore.FieldValue.serverTimestamp(),

一切正常,我可以看到高度和创建日期,我还可以在 firebase 上添加带有日期的高度,唯一的问题是每次创建高度时都会出现此错误:

null 不是对象(评估'props.item.createdAt.toDate')]

即使有错误,该对象也会在 firebase 中创建,但是如果我删除显示日期的代码部分,它可以正常工作而不会出现任何错误。

我该如何解决?

标签: reactjsnative

解决方案


推荐阅读