【问题标题】:How to correctly use getStaticProps for firebase?如何正确地将 getStaticProps 用于 firebase?
【发布时间】:2021-05-09 20:40:33
【问题描述】:

我对 Next.js 非常陌生,无法让 getStaticProps 正常工作。

import firebase from '../firebase'

export default function Home({ posts }) {
  return (
    <div>
      <h1>All Posts</h1>
      {posts.map((post) => (
        <div key={post.pid}>{post.title}</div>
      ))}
    </div>
  )
}

export const getStaticProps = async () => {
  let posts = []
  firebase
    .firestore()
    .collection('posts')
    .orderBy('createdAt', 'desc')
    .get()
    .then(function (querySnapshot) {
      querySnapshot.forEach(function (doc) {
        console.log(doc.data().title)
        console.log(doc.data().pid)
        posts.push({
          pid: doc.data().pid,
          title: doc.data().title,
        })
      })
      console.log(posts)
    })
    .catch(function (error) {
      console.log('Error getting documents: ', error)
    })

  return {
    props: {
      posts,
    },
  }
}

当我在getStaticPropsconsole.log(posts) 时,我可以看到帖子,但不知何故它没有显示在主页组件中。任何帮助将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    问题是您没有等待从get() 返回的承诺完成,因此返回一个空的posts(您只在承诺返回后填充该变量,在then 部分)。事实上,如果你把 console.log(posts) 放在 return 之前(而不是放在 observable 的 then 部分),你会看到它在那里是空的。

    所以你只需要await它...类似(显然未经测试):

    export const getStaticProps = async () => {
        let posts = []
        try 
        {
          // await the promise
          const querySnapshot = await firebase
            .firestore()
            .collection('posts')
            .orderBy('createdAt', 'desc')
            .get();
        
          // "then" part after the await
          querySnapshot.forEach(function (doc) {
            console.log(doc.data().title)
            console.log(doc.data().pid)
            posts.push({
              pid: doc.data().pid,
              title: doc.data().title,
            })
          })
          console.log(posts)
        } catch(error) {
            // catch part using try/catch
            console.log('Error getting documents: ', error)
            // return something else here, or an empty props, or throw an exception or whatever 
        }
    
        return {
            props: {
              posts
            }
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2011-09-17
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 2021-08-15
      • 2019-03-14
      • 2019-04-05
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多