javascript - 如何正确使用 Firestore 的 serverTimestamp 来设置正在订阅的文档的值?
问题描述
概述/环境:
- 一个 react-native 项目 v0.61.5
- 使用
react-native-firebase
包 - 使用 action 填充 redux 状态,通过 props 显示 firestore 数据
目标:
- 收听文件集
- 使用 Firestore
FieldValue.serverTimestamp()
设置所述集合中文档的时间值 toMillis()
在快照侦听器中使用 serverTimestamp 的函数
观察/错误:
- 在所述集合中创建文档时,该文档可以正常创建,并且显示正常
- 在创建 doc/time 值时,应用程序由于
doc.get('time').toMillis()
快照侦听器内部的调用而崩溃:TypeError: null is not an object (evaluating 'doc.get('time').toMillis()')
到目前为止,我已经尝试了这里提到的所有建议:为什么 Firestore 的 'doc.get('time').toMillis' 会产生空类型错误?
似乎没有什么可以解决此崩溃。
这是快照侦听器:
.onSnapshot({ includeMetadataChanges: true }, (querySnapshot) => {
if (querySnapshot.metadata.fromCache && querySnapshot.metadata.hasPendingWrites) {
// ignore cache snapshots where new data is being written
return;
}
const messages = [];
querySnapshot.forEach((doc) => {
const estimateTimestamps = { serverTimestamps: 'estimate' }
const msg = doc.data();
msg.docId = doc.id;
msg.time = doc.get('time', estimateTimestamps).toMillis();
const timestamp = doc.get('time', estimateTimestamps);
if (timestamp) {
msg.time = timestamp.toMillis();
} else {
debugger
console.error(doc.id + ' is missing "time" field!');
}
messages.push(msg);
});
dispatch({ type: types.LOAD_MSGS, payload: messages });
resolve();
});
以下是文档的创建方式:
const addMsg = (msg, userConvos) => {
return firebase.firestore().collection('messages').add({
time: firebase.firestore.FieldValue.serverTimestamp(),
sender: msg.sender,
read: false,
userConvos: [userConvos.sender, userConvos.receiver],
content: {
type: 'msg',
data: msg.text
}
});
};
我知道该值可能在短时间内为空,我需要一种方法来防止应用程序在此期间崩溃。
解决方案
错误将您指向此代码:
doc.get('time').toMillis()
意思是doc.get('time')
返回 null,因此,您不能调用toMillis()
它。
您链接到的问题的答案确切地解释了为什么会这样。如果还是不清楚,建议再读一遍。如果服务器时间戳尚未到达服务器,则时间戳将为空。
也许您打算像这样检查时间戳是否为空,而无需调用toMillis()
:
msg.isPending = doc.get('time') === null;
推荐阅读
- c# - 使用 SimpleInjector 在 IExceptionFilter 中注入 Logger
- c++ - C++ 应用程序缺少 winrt::Windows::Storage::Streams::DataWriter
- c# - 搜索所有文件夹和子文件夹
- arrays - 反应推送数组到状态
- javascript - 将表格行复制到剪贴板 - 仅复制第一页
- c++ - 是否可以保存带有参数的函数指针以供以后使用?
- python - 循环遍历 2 个 numpy 数组并将它们连接起来
- uwp - 将 xBind 与 MapElementLayer 一起使用
- python - Paramiko 如何等到 cmd 完成。(不能使用 exec_command)
- javascript - JavaScript 中两个深层对象的交集