【问题标题】:React-native, firestore: how to update component state when an instance variable changes its valueReact-native,firestore:当实例变量更改其值时如何更新组件状态
【发布时间】:2020-07-14 02:57:15
【问题描述】:

我使用 Google Firestore 作为 React Native 的后端。

我创建了一个类,我在其中存储有关 firestore 的所有内容(方法、信息等),并在该类中使用实时更新 (https://firebase.google.com/docs/firestore/query-data/listen):

class Fire{
  constructor() {
    this.user = {};  //is defined when the user log in
    this.userDocument = null;
  }

  _getRealTimeData = () => {
    const realTimeDatabaseRef = db.collection("users").doc(this.user.uid);
    realTimeDatabaseRef.onSnapshot(doc => {
      try {
        if (doc.exists) {
         this.userDocument = doc.data();
        } else {
          this.userDocument = null;
        }
      } catch (error) {
        console.log(error);
        this.userDocument = null;
      }
    });
  };
}
Fire = new Fire();
export default Fire;

所以这工作正常,每当我更新我的 firestore 数据库时,我都会自动获取新值并将其存储在: this.userDocument

问题是当这个值改变时 react-native 组件并没有更新,显然是因为该组件的状态没有更新。

所以我的问题是,如何通知我的组件 Fire 类中“this.userDocument”的值已更改?所以我可以通过 this.setState({userDocument: Fire.userDocument}) 更新状态。

注意:现在我只是从 componentDidMount() 中的“this.userDocument”获取数据:

import Fire, { db } from "../../Fire";
export default class Profile extends Component {
    state={ userDocument:null }
    componentDidMount(){
      Fire._getRealTimeData()
      this.setState({userDocument: Fire.userDocument})
    }
  render(){...whatever I render}
}

【问题讨论】:

  • 你在哪里打电话_getRealTimeData
  • 抱歉忘记写了,现在正在编辑。在 componentDidMount()

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


【解决方案1】:

您在 { Profile } 的状态仅在 componentDidMount 更改,因此没有任何信息告诉该组件它应该再次呈现。

我不知道用户在 firebase 上更新他的个人资料数据的操作是什么,但在最后添加类似


  if (this.state.userDocument != Fire.userDocument)
                   this.setState({userDocument: Fire.userDocument})

如果动作在 { Profile } 中,如果它在其中一个孩子中,则将此函数和状态作为道具发送,或者当然将 Redux 添加到项目中,然后将状态存储在那里,并将组件连接到存储,它会更新自动

【讨论】:

    【解决方案2】:

    a) 您可以将回调传递给 Fire 并调用它来设置 Profile 组件的状态。

    b) 将 Promise 传递给 Fire 组件并解析/拒绝它以将状态设置为 Profile 组件。

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      相关资源
      最近更新 更多