首页 > 解决方案 > 实现 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,
                            });
                        }
                    );
                }
            });
    };

谢谢

标签: reactjsfirebasegoogle-cloud-firestore

解决方案


您正在将所有城市保存到您的州中。使用它来添加或更新新的(或更新的)城市。

也许你可以尝试这样的事情:

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 });
  });
});

推荐阅读