Firestore onSnapshot如何侦听React-Native中的更改? [英] How does a Firestore onSnapshot listens for changes in React-Native?

查看:50
本文介绍了Firestore onSnapshot如何侦听React-Native中的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在很多地方看到人们将侦听器代码放置在 componentDidMount 内,但是我想知道它是如何工作的,因为 componentDidMount 仅被调用一次,因此,它应该只获取一次.当Firestore中发生更改时,如何再次获取?

I have seen in multiple places people placing the listener code inside the componentDidMount, however, I am wondering how does it work since componentDidMount is called only once, therefor, it should fetch only once. How does it fetches again when changes happen in Firestore?

示例代码:

componentDidMount() {
  if(this.state.screen === 7){
        var query = firestore().collection('Collection').doc().collection('subcollection');
            query = query.where('act', '==', 1);
            query = query.where('city', '==', this.state.selected_city);
            query = query.orderBy('update_time', 'desc');
            query = query.limit(10);

            query.onSnapshot({
                error: (e) => this.setState({ errorMessage: e, refreshingPatients: false }),
                next: (querySnapshot) => {
                    var dataSource = querySnapshot.docs.map(doc => { return { ...doc.data(), doc_id: doc.id } });                       
                    var lastVisiblePatient = dataSource[dataSource.length - 1].doc_id;
                    this.setState({
                        dataSource: dataSource,
                        lastVisiblePatient: lastVisiblePatient,
                        refreshingPatients: false,
                    });
                },
            });
    }
 }

编辑:添加了示例代码.我想一直聆听Firestore DB的变化.那是正确的方法吗?如果是,它如何工作,因为 componentDidMount 仅被调用一次?注意:我仅在屏幕状态设置为7时才收听Firestore.

EDIT: added an example code. I want to listen to changes of Firestore DB all the time. Is that the correct way of doing it? If yes, how does it work because componentDidMount is only called once? Note: I am only listening to Firestore when screen state is set to 7.

推荐答案

您的 componentDidMount 实际上仅被调用一次,但是您在其中附加了永久侦听器.因此,您将在 onSnapshot.next 中指定的处理程序立即与数据库中的初始数据一起调用,此后,每次与查询匹配的数据更改时,都会调用该处理程序.

Your componentDidMount is indeed only called once, but you're attaching a permanent listener in there. So the handler that you specify in onSnapshot.next is called right away with the initial data from the database, and after that each time that the data matching the query changes.

这篇关于Firestore onSnapshot如何侦听React-Native中的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆