NextJS:如何正确使用 getStaticProps for firebase

时间:2021-02-05 13:44:21

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

我对 NextJS 非常陌生,无法让 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,
    },
  }
}

当我在 getStaticProps 中使用 console.log(posts) 时,我可以看到这些帖子,但不知何故它没有显示在 Home 组件中。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

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

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

await