reactjs - 实现 onSnapshot 函数以获取 reactjs 代码中的实时更新
问题描述
就我而言,我想实现 onSnapshot 函数来获取实时更新,所以这是我现在可以使用的示例代码:
db.collection("Cities").onSnapshot((snapshot) => {
snapshot.docs.forEach((doc) => {
console.log(doc.data());
});
});
但是现在,我该如何将它实现为以下代码
getMyInfo = () => {
db.collection("Cities")
.limit(8)
.get()
.then((docs) => {
if (!docs.empty) {
let AllCities = [];
docs.forEach(function (doc) {
const city = {
id: doc,
...doc.data(),
};
AllCities.push(city);
});
this.setState(
{
cities: AllCities,
},
() => {
this.setState({
isLoaded: true,
});
}
);
}
});
};
谢谢
解决方案
您正在将所有城市保存到您的州中。使用它来添加或更新新的(或更新的)城市。
也许你可以尝试这样的事情:
db.collection("Cities").onSnapshot((snapshot) => {
snapshot.docs.forEach((doc) => {
const updatedCity = doc.data();
const cities = [...this.state.cities];
const index = this.state.cities.findIndex(c => c.id === updatedCity.id);
if (index >= 0) {
cities[index] = updatedCity;
} else {
cities.push(updatedCity);
}
this.setState({ cities });
});
});
推荐阅读
- elasticsearch - updateSearchIndexConfig.php
- docker - 容器无法连接到互联网
- javascript - 参数列表后缺少错误 - Selenium Python(执行 Javascript)
- ios - 我是否需要物理 iPhone 来编译和分发 IOS 应用程序?
- c# - 错误:未定义或导入预定义类型“System.Range”
- python - VSCode FileNotFoundError
- haskell - 如何让 GHCi 重新加载包括本地依赖库中的更改?
- java - Spring Boot 应用程序问题
- c++ - 如何在 C++ 中创建具有不同行大小的向量?
- javascript - 如何以角度制作路线