【发布时间】:2021-05-09 10:27:52
【问题描述】:
我正在使用 Firestore 创建一个聊天应用程序,我使用 Flatlist 并使用 onSnapshot() 进行查询以实时显示发送者和接收者
我下面的示例查询是这样的:
const ChatMessages = useCallback(() => {
privateMessage
.doc(chatId)
.collection('messages')
.orderBy('createdAt', 'asc')
.onSnapshot((querySnapshot) => {
const messageList = [];
querySnapshot.forEach((doc) => {
messageList.push(doc.data());
})
setMessages(messageList);
}, error => {
console.log(error)
})
}, [chatId])
然后在我的示例平面列表中,我有将显示在屏幕上的用户显示名称、消息和创建的时间:
<FlatList
data={messages}
keyExtractor={(item, index) => String(index)}
removeClippedSubviews={false}
renderItem={({ item }) => (
<View>
<Text style={chatstyle.pmdate}>
{item.createdAt.toDate().toDateString()}
</Text>
<Text>
{item.displayName}
</Text>
<Text>
{item.message}
</Text>
</View>
)}
/>
我想显示时间和日期,但是在使用 onSnapshot() 时我得到 null is not an object (evalating 'item.createdAt.toDate') 错误但是当我删除 {item.createdAt.toDate().toDateString ()} 一切都好。我尝试了 get() 查询,时间戳工作正常,但它当然不是实时的。
使用 onSnapshot() 显示时间戳的正确方法是什么?
【问题讨论】:
-
您能展示一下您是如何创建消息文档的吗?
-
我只是用 firebaseMessage.doc(id).set(userMessages).catch(e => {console.log(e))} 发送消息
-
我使用的是 const newDate = firebase.firestore.FieldValue.serverTimestamp() 这个在使用 onSnapshot() 显示日期时不能直接工作
标签: javascript firebase react-native google-cloud-firestore