我在 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
时间戳已成功获取。
最佳答案
created_At
是一个对象,正如您在日志中清楚显示的那样。如果您想将其转换为日期,请选择其中一个字段。因此 created_at.nanoseconds
将为您提供一个可以转换的时间戳。
我不确定toDate()
是什么,这不是原生js方法,你指的是moment js吗?如果您想将时间戳转换为日期,您应该尝试 new Date(created_at.nanoseconds)
关于javascript - 无法使用未定义的 Firestore 时间戳 ('toDate'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60050339/