【问题标题】:Refresh sub-collection automatically in React Native when using Firestore使用 Firestore 时在 React Native 中自动刷新子集合
【发布时间】:2019-04-10 16:28:15
【问题描述】:

我正在将记录添加到我在屏幕上呈现的 firebase 子集合中。我遇到的问题是,一旦我执行 firestore.add(),新记录就不会被拉出并呈现在屏幕上。我知道 firestore/firebase 会自动提取新记录并重新渲染显示它们的实际屏幕,但在我的情况下,它不会那样工作。 完成 firestore.add() 后,我是否必须调用一些命令来更新实际屏幕?

谢谢

【问题讨论】:

  • 如果您使用onSnapshot 监听器,它们应该会在基础数据更改时自动被调用。如果您没有遇到这种情况,请编辑您的问题以包含重现问题所需的最少完整代码。

标签: react-native google-cloud-firestore


【解决方案1】:

您必须订阅集合更新才能在应用中实际看到更新。

根据documentation

您可以使用 onSnapshot() 方法收听文档。

可以使用以下代码实现:

state = {
  loading: true,
  users: []
}

componentDidMount() {
  this.unsubscribe = firebase.firestore().collection('users').onSnapshot(this.onCollectionUpdate) 
}

componentWillUnmount() {
  // we have to unsubscribe when component unmounts, because we don't need to check for updates
  this.unsubscribe()
}

onCollectionUpdate = (querySnapshot) => {
  // we have to update the state
  const users = []
  querySnapshot.forEach((document) => {
    const { firstName, lastName } = document.data()

    users.push({
      key: document.id,
      document,
      firstName,
      lastName
    })
  })

  this.setState({ 
    users,
    loading: false
 })
}

更详细的例子可以在here找到。

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2021-05-08
    • 2020-02-15
    相关资源
    最近更新 更多