尝试添加onSnapshot选项以获取实时更新firebase reactjs

时间:2020-05-09 23:29:49

标签: reactjs firebase google-cloud-firestore

我正在尝试在代码中添加onSnapshot选项,我在控制台日志中添加了数据,在此简单代码中可以正常工作:

db.collection("cities")
    .doc(cid)
    .onSnapshot(function(doc) {
        console.log("Current data: ", doc.data());
    });

因此,现在我如何才能将此功能添加到以下代码中:

 getCityByID = (cid) => {
        db.collection("cities")
            .doc(cid)
            .get()
            .then((doc) => {
                if (doc.exists) {
                    this.setState(
                        {
                            city: doc.data(),
                        },
                        () => {
                            this.setState({
                                isLoaded: true,
                            });
                        }
                    );
                } else {
                    this.props.history.push({ pathname: "/" });
                }
            });
    };
请提供任何建议。非常感谢

1 个答案:

答案 0 :(得分:0)

哦!我找到了一个解决方案,我不知道这是否正确,但是可以解决问题。

db.collection("cities")
            .doc(cid)
            .onSnapshot((doc) => {
                this.setState(
                    {
                        city: doc.data(),
                    },
                    () => {
                        this.setState({
                            isLoaded: true,
                        });
                    }
                );
            });