【问题标题】:Type 'Promise<QuerySnapshot<DocumentData>>' must have a '[Symbol.iterator]()' method that returns an iterator类型 'Promise<QuerySnapshot<DocumentData>>' 必须有一个返回迭代器的 '[Symbol.iterator]()' 方法
【发布时间】:2021-10-25 18:48:05
【问题描述】:

我正在使用 NextJS 和 Typescript 开发一个 Firebase 项目。我正在尝试从 Firestore 数据库中获取数据,但出现此错误 Type 'Promise&lt;QuerySnapshot&lt;DocumentData&gt;&gt;' must have a '[Symbol.iterator]()' method that returns an iterator.

这是我用来从数据库中获取数据的代码

const postsRef = collection(db, "discussions");
query(postsRef, orderBy("createdAt"), limit(20));
const [posts]  =  getDocs(postsRef)

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore next.js


    【解决方案1】:

    您的 getDocs 没有返回数组,这就是您收到此错误的原因。 QuerySnapshot 是一种自定义 Firebase 类型,它具有 forEach(类似于数组),但不是数组。所以你需要使用forEach 遍历它:

    const postsRef = collection(db, "discussions");
    query(postsRef, orderBy("createdAt"), limit(20));
    // I'm guessing you need await here too?
    const postDocs  =  await getDocs(postsRef)
    
    let posts = []
    postDocs.forEach((postDoc) => {
      posts = [...posts, {
        ...postDoc.data(),
        id: postDoc.id,
      }]
    })
    

    【讨论】:

    • 我已粘贴代码,但收到此错误Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    • 这与此代码无关。这个新错误是一个反应错误,表明您正在尝试将承诺或对象作为反应组件传递,但您不能这样做。无论哪种方式,这是您应该询问的一个新问题,您需要发布更多代码,因为它与您发布的 Firebase 代码无关(至少不是直接相关 - 需要您的一些 React 代码来调试它)
    • @I'mJoeToo 听起来 OP 是将此代码内联添加到其组件中,而不是将其包装在 useEffect/useAsync/useAsyncEffect 中。
    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多