【发布时间】:2019-08-14 11:21:24
【问题描述】:
我正在开发一个使用 Firebase 的 Firestore 作为后端的 React Native 应用程序。现在,每次收到新消息时,我都会从 Firestore 中获取所有消息并更新我的状态,尽管它只是收到了一条新消息。
function listenCurrentChat(dispatch, chatID) {
const address = "chats/" + chatID + "/messages";
firebase.firestore().collection(address).orderBy('createdAt')
.onSnapshot(function (querySnapshot) {
dispatch({
type: CLEAR_MESSAGES,
payload: {
chatID: chatID,
}
});
querySnapshot.forEach(function (doc) {
//local
if (doc.metadata.hasPendingWrites) {
dispatch({
type: ADD_MESSAGE,
payload: {
chatID: chatID,
message: {...doc.data(), createdAt: new Date()}
}
});
} else {
dispatch({
type: ADD_MESSAGE,
payload: {
chatID: chatID,
message: {...doc.data(), createdAt: doc.data().createdAt.toDate()}
}
});
}
});
});
}
显然这很糟糕,因为我只为一条新消息使用了多次阅读,而且用户体验一点也不好,因为总是有延迟。我还尝试将这些实时侦听器的地址保存在 redux 状态,并从最后一条消息的时间戳进行侦听,但这似乎也不是一个好的解决方案,因为我不再考虑以前的消息可以编辑。什么是更新 React Native 部分的聊天对话的好方法,以便我使用尽可能少的 Firestore 读取?
提前致谢。
【问题讨论】:
标签: javascript firebase react-native google-cloud-firestore