【发布时间】:2021-03-04 11:49:46
【问题描述】:
我想检索与用户位置相关的产品列表,为此我使用 Geofirestore 并更新我的平面列表
当我拥有前 10 个最接近的集合时,我会循环以获取每个子集合。
我设法很好地更新了我的状态,但是每次在其他地方修改我的集合时,它不会更新我的列表,而是复制我已修改的对象并将其添加(更新)到我的列表末尾并保留该列表中的旧对象也是如此。
例如:
const listListeningEvents = {
A: {Albert, Ducon}
B: {Mickael}
}
另一个用户修改了'A'并删除了'Ducon',我会得到:
const listListeningEvents = {
A: {Albert, Ducon},
B: {Mickael},
A: {Albert}
}
而不是:
const listListeningEvents = {
A: {Albert},
B: {Mickael},
}
那是我的 useEffect:
useEffect(() => {
let geoSubscriber;
let productsSubscriber;
// 1. getting user's location
getUserLocation()
// 2. then calling geoSubscriber to get the 10 nearest collections
.then((location) => geoSubscriber(location.coords))
.catch((e) => {
throw new Error(e.message);
});
//Here
geoSubscriber = async (coords) => {
let nearbyGeocollections = await geocollection
.limit(10)
.near({
center: new firestore.GeoPoint(coords.latitude, coords.longitude),
radius: 50,
})
.get();
// Empty array for loop
let nearbyUsers = [];
// 3. Getting Subcollections by looping onto the 10 collections queried by Geofirestore
productsSubscriber = await nearbyGeocollections.forEach((geo) => {
if (geo.id !== user.uid) {
firestore()
.collection("PRODUCTS")
.doc(geo.id)
.collection("USER_PRODUCTS")
.orderBy("createdDate", "desc")
.onSnapshot((product) => {
// 4. Pushing each result (and I guess the issue is here!)
nearbyUsers.push({
id: product.docs[0].id.toString(),
products: product.docs,
});
});
}
});
setLoading(false);
// 4. Setting my state which will be used within my Flatlist
setListOfProducts(nearbyUsers);
};
return () => {
if (geoSubscriber && productsSubscriber) {
geoSubscriber.remove();
productsSubscriber.remove();
}
};
}, []);
多年来,我一直在努力使其正常工作,我快要疯了。
所以我梦想着两件事:
- 能够在不复制修改对象的情况下更新我的状态。
- (奖励)当我向下滚动到平面列表时,找到一种方法来获取下一个最近的 10 个点。
【问题讨论】:
标签: javascript reactjs firebase react-native google-cloud-firestore