javascript - 无法使用未定义的 Firestore 时间戳 ('toDate')

标签 javascript reactjs firebase google-cloud-firestore

我在 React 中使用 Firestore。这个应用程序节省了 created_at datetime 作为 Firestore 的 Timestamp 对象,如下所示。使用firebase.firestore.FieldValue.serverTimestamp() .

export function createComment(uid, values, count) {
  return dispatch => {
    commentsRef
      .add({
        uid: uid,
        content: values.content,
        created_at: firebase.firestore.FieldValue.serverTimestamp()
      })
      .then(function() {
        roomsRef
          .doc(uid)
          .update({
            comment_count: Number(count) + 1
          })
          .then(() => {
            dispatch({ type: CREATE_COMMENT });
          });
      });
  };
}

但是当我尝试显示created_at时发生错误时间戳。

// Fetch comments
export function fetchComments(uid) {
  return dispatch => {
    commentsRef
      .where("uid", "==", uid)
      .get()
      .then(snapshot => {
        const comments = snapshot.docs.map(doc => {
          return {
            const timstamp = doc.data().created_at.toDate();
            // error occurs
            ...doc.data(),
            id: doc.id,
            timestamp: timestamp
          };
        });
        return comments;
      })
      .then(comments => {
        dispatch({ type: FETCH_COMMENTS, payload: comments });
      });
  };
}

错误:

TypeError: Cannot read property 'toDate' of undefined

时间戳已成功获取。

enter image description here

最佳答案

created_At 是一个对象,正如您在日志中清楚显示的那样。如果您想将其转换为日期,请选择其中一个字段。因此 created_at.nanoseconds 将为您提供一个可以转换的时间戳。

我不确定toDate()是什么,这不是原生js方法,你指的是moment js吗?如果您想将时间戳转换为日期,您应该尝试 new Date(created_at.nanoseconds)

关于javascript - 无法使用未定义的 Firestore 时间戳 ('toDate'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60050339/

相关文章:

javascript - 使用 angularjs Controller 删除 html 中的 target 属性

javascript - NextJS : Reload iFrame from another component

swift - 使用自定义解码器解码 Firestore 结构时获取 DocumentID

javascript - 有条件呈现的 Web 组件和样式表链接

javascript - 将 Canvas 分成相同宽度和高度的空间

Javascript Button - onClick 之后不会调用方法

javascript - onChange 事件上的模糊 Material UI 选择组件

javascript - 在 React 中父级触发的事件中将数据传递给子级

firebase - 有没有办法在父文档不为空的情况下在 Firestore 中添加自定义路径子集合?

javascript - Web Firebase Cloud Messaging - 如何从客户端订阅主题?