javascript - 在 useEffect 中使用“array-contains”的 react-native-firebase 查询不断刷新组件
问题描述
我只是试图发出请求以仅获取包含当前用户 ID 的线程。
如果我删除我的“where”查询,我可以获取所有线程。
有我的代码:
useEffect(() => {
const unsubscribe = firestore()
.collection('THREADS')
// query is empty
.where('usersIds', 'array-contains', ['60ddd70c7a3a1e8e62d14dac'])
.orderBy('latestMessage.createdAt', 'desc')
.onSnapshot(querySnapshot => {
const threadsQueried = querySnapshot
? querySnapshot.docs.map(documentSnapshot => {
return {
...documentSnapshot.data(),
};
})
: null;
setThreads(threadsQueried);
if (loading) {
setLoading(false);
}
});
return () => unsubscribe();
});
我已经尝试过不将我的 id 放入数组中,但组件不断刷新,如下所示:
.where('usersIds', 'array-contains', '60ddd70c7a3a1e8e62d14dac')
我的火力基地数据:
我已经在这里检查了https://stackoverflow.com/a/59053018/9300663
在这里https://stackoverflow.com/a/59215461/9300663
编辑:所以当 id 在查询中没有括号('60ddd70c7a3a1e8e62d14dac')时它可以工作
但我的组件不断刷新。
如果我向我的 useEffect 添加一个空数组或一个具有依赖关系的数组,则查询不再起作用。
编辑2:查询正在工作,但被调用了两次,第二次返回'null',这正在清空我的状态。
解决方案
因此,当我尝试使用 get() 而不是 onSnapshot() 获取 Firebase 查询的另一种方法时,我找到了解决方案:
firestore()
.collection('THREADS')
.where('usersIds', 'array-contains', user.id)
.orderBy('latestMessage.createdAt', 'desc')
.get()
.then(querySnapshot => {
const threadsQueried = querySnapshot.docs.map(documentSnapshot => {
return {
...documentSnapshot.data(),
};
});
setThreads(threadsQueried);
'get()' 的问题是查询只工作一次,并且在创建新线程时不会更新。
但它让我有一个 Firebase 错误,要求我创建索引:“usersIds”和“latestMessage.createdAt”。创建它们之后,我能够重用我的旧代码并且现在一切正常。
useEffect(() => {
const unsubscribe = firestore()
.collection('THREADS')
.where('usersIds', 'array-contains', user.id)
.orderBy('latestMessage.createdAt', 'desc')
.onSnapshot(querySnapshot => {
const threadsQueried = querySnapshot.docs.map(documentSnapshot => {
return {
...documentSnapshot.data(),
};
});
setThreads(threadsQueried);
});
return () => unsubscribe();
}, []);
推荐阅读
- scala - Spark Shell - 清除进口
- python - 构建一个 trie,其中每个节点都包含一个标记而不是 python 中的一个字符
- android - 设置多个地图点
- javascript - Leaflet Maps:如何使用数组中的内容创建带有键/值对的叠加层?
- maven - HTML 页面不显示在 Springboot 应用程序上
- angular - RxJS 操作符执行顺序
- c - 回文函数,不在 C 中返回值
- css - 从页面中心开始“爆炸”的轻动画
- python - 在扩展包含的列中查询 EXACT 单词的 Pandas 数据框
- c# - 方法“CommonCreateArrayTypeSymbol”没有实现