我有一个正在查询的文档集合,按“计数”排序,并收听实时更新。然而,每次任何文档(例如“count”)更新时,整个文档数组都会按“count”重新呈现和重新排序。我想监听更新,但避免每次更新都重新渲染数组。
这是我提出的请求的简化版本。“queriedData”是我将在 JSX 中循环的内容。
useEffect(() => {
const unsubscribe = firebase
.firestore()
.collection("someCollection")
.orderBy("count", "desc")
.onSnapshot(collection => {
const newArray = [];
collection.forEach(document => {
const { name, count } = document.data();
newArray.push({
key: document.id,
name,
count
});
});
setQueriedData(newArray); // <-- array in the JSX
});
return () => {
unsubscribe();
};
}, [queriedData]);
Run Code Online (Sandbox Code Playgroud)
我想过尝试改变呈现查询数据数组的方式,但不知道如何循环查询 Firestore 数据,而不是像我在这里所做的那样先将其放入数组中。
我正在学习 Angular 并阅读文档,但我很困惑为什么在下面的变量声明中使用按位 OR 运算符product。这条线是什么product: Product | undefined意思?
export class ProductDetailsComponent implements OnInit {
product: Product | undefined;
/* ... */
}
Run Code Online (Sandbox Code Playgroud) 为了显示加载进度,我试图在初始获取时将 onSnapshot 调用包装在一个 promise 中。数据加载正确,但实时更新无法正常运行。
有没有办法使用 onSnapshot 方法实现这种类型的功能?
这是我的初始数据抓取。在实现承诺包装器之前,实时更新功能正常:
const [heroesArr, setHeroesArr] = useState([]);
const db = firebase.firestore();
const dbError = firebase.firestore.FirestoreError;
useEffect(() => {
const promise = new Promise((resolve, reject) => {
db.collection("characterOptions")
.orderBy("votes", "desc")
.onSnapshot(coll => {
const newHeroes = [];
coll.forEach(doc => {
const {
name,
votes
} = doc.data();
newHeroes.push({
key: doc.id,
name,
votes
});
});
if(dbError) {
reject(dbError.message)
} else {
resolve(newHeroes);
}
});
});
promise
.then(result => {
setHeroesArr(result);
})
.catch(err => {
alert(err); …Run Code Online (Sandbox Code Playgroud)