我正在使用Cloud数据库来执行一些地理哈希查询(在地火库的帮助下)。看起来,需要多个查询才能执行geohashing,确切地说,需要四个查询:
import { geohashQueryBounds } from "geofire-common";
import { onSnapshot, query, orderBy, startAt, endAt } from "firebase/firestore";
// Find cities within 100km of Milan
const center = [45.464664, 9.18854];
const radiusInM = 500 * 1000;
// Each item in 'bounds' represents a startAt/endAt pair. We have to issue
// a separate query for each pair. There can be up to 9 pairs of bounds
// depending on overlap, but in most cases there are 4.
const bounds = geohashQueryBounds(center, radiusInM);
const queries = [];
for (const bound of bounds) {
console.log("bound:", bound);
const q = query(
locationsCol,
orderBy("geohash"),
startAt(bound[0]),
endAt(bound[1])
);
queries.push(q);
}onSnapshot可用于侦听实时更新,然后更新状态:
queries.map((query) => {
onSnapshot(query, (snapshot) => {
// update state here
});
});我如何才能一次更新本地状态,而不是通过四个不同的onSnapshots呢?每次调用onSnapshot时,状态都会被覆盖,这不是我想要的。
发布于 2022-09-26 14:46:23
要覆盖任意区域和半径,需要4到9个地哈希范围。如果只想在处理完所有快照后才更新状态,则需要自己跟踪这些查询的完成情况。
使用getDocuments调用而不是onSnapshot最容易做到这一点,因为在这种情况下可以使用Promise.all:
const promises = queries.map((query) => getDocs(query, (snapshot));
Promise.all((promises)).then((snapshots) => {
// process all snapshots and update state
});您也可以继续使用onSnapshot,但在这种情况下:
onSnapshot回调至少触发一次之后才更新状态。onSnapshot可以多次触发,所以您可能会在稍后更新状态。https://stackoverflow.com/questions/73855533
复制相似问题