【问题标题】:Uncaught (in promise) TypeError: querySnapshot.forEach is not a function React NativeUncaught (in promise) TypeError: querySnapshot.forEach 不是 React Native 的函数
【发布时间】:2021-12-30 17:31:06
【问题描述】:

我在 Firebase 上有一个“用户”集合。这个集合中有一些我想在屏幕上呈现的字段

我有一个 Home 类,其中包含以下功能:

const db = firebase.firestore();

    
export class Home extends Component {
  constructor(props) {
    super()
  }
  componentDidMount(){
     db.collection('/users')
     .doc(firebase.auth().currentUser.uid)
     .get()
     .then(querySnapshot => {
        querySnapshot.forEach(uid => {
        let data = uid.data();
           console.log(data);
        })
      })
  }
}

没有.doc(firebase.auth().currentUser.uid),我会在屏幕上获得所有用户的所有字段,但是当我添加它时,为了获取每个用户的详细信息,我遇到错误“未捕获(承诺中)TypeError:querySnapshot.forEach不是函数”。提前感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    您在DocumentReference 上使用get(),它返回一个DocumentSnapshot,其中仅包含单个文档的数据,并且上面没有任何forEach 方法。所以直接在快照上使用data() 就可以了。尝试重构代码如下所示:

    componentDidMount() {
      db.collection('/users')
        .doc(firebase.auth().currentUser.uid)
        .get()
        .then((docSnapshot) => {
          console.log(docSnapshot.data())
        })
    }
    

    如果您尝试从用户集合中获取所有文档,请在CollectionReference 上使用get()(基本上删除.doc(uid)),如下所示:

    componentDidMount() {
      db.collection('/users')
        .get()
        .then((querySnapshot) => {
          querySnapshot.forEach((doc) => {
            console.log(doc.data())
          })
        })
    }
    

    【讨论】:

    • 我明白你的意思。我没有意识到我正在查询文件。感谢您的帮助,它成功了:)
    • 刚刚做到了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多