【问题标题】:How to update a component without refresh/reload in react-native when we fetch/update data from firebase?当我们从 firebase 获取/更新数据时,如何在 react-native 中更新组件而不刷新/重新加载?
【发布时间】:2020-07-13 10:25:29
【问题描述】:

我正在从我的 react 本机应用程序中的组件 A 更新 firebase 集合中的一些数据。例如,我正在更新 firebase 集合 X 中的 name 参数。名称的更新是从组件 A 完成的。组件 B 正在从同一个集合 X 中获取名称。但是要查看组件 B 中的更改,我必须重新加载应用程序或再次刷新应用程序。但我想在不刷新或重新加载应用的情况下查看更改。

组件 A

    async setName(){
    await firestore()
    .collection('set_name')
    .doc(auth().currentUser.uid)
    .update({
      name: this.state.name}).then( () => {
        console.log('name updated')
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
}

组件 B

    componentDidMount(){
      this.getName();
    }

    async getName(){
    let name;
    await firestore()
    .collection('set_name')
    .doc(auth().currentUser.uid)
    .get().then(function(doc){
        this.setState({name:doc.data()}))
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
}

我可以从组件 B 中的 firebase 获取数据,但要查看更改,我必须重新加载组件。但我不想重新加载看到组件 B 的任何变化。

【问题讨论】:

    标签: javascript reactjs firebase react-native google-cloud-firestore


    【解决方案1】:

    我认为您应该使用 onSnapShot 函数来获取实时更新并设置组件状态。

    试试这个方法

    组件 B

    componentDidMount(){
       firestore()
        .collection('set_name')
        .doc(auth().currentUser.uid)
        .onSnapshot(function(doc) {
            this.setState({name:doc.data()}))
        });
    }
    

    【讨论】:

      【解决方案2】:

      您需要收听来自 Firestore 的实时更新。当您执行写入时,您的侦听器将在数据发送到后端之前收到新数据的通知。所以不用在组件 B 中使用.get(),你可以修改函数如下。

       db.collection('set_name')
          .doc(auth().currentUser.uid)
          .onSnapshot(function(doc) {
             this.setState({name:doc.data()}))
          });
      

      【讨论】:

        猜你喜欢
        • 2021-05-29
        • 2021-05-08
        • 1970-01-01
        • 2011-11-29
        • 2022-07-09
        • 2023-01-28
        • 2021-04-03
        • 2021-03-02
        • 2017-05-09
        相关资源
        最近更新 更多