如何正确使用 Firebase 的 getStaticProps?

Dar*_*ong 1 javascript reactjs next.js google-cloud-firestore

我对 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,
    },
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Jcl*_*Jcl 6

问题是您没有等待返回的 Promiseget()完成,因此返回一个空值posts(您仅在 Promise 返回后填充该变量then)。事实上,如果您将右侧放在console.log(posts)返回之前(而不是放在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
        }
    }
}

Run Code Online (Sandbox Code Playgroud)