繁体   English   中英

NextJS:firebase如何正确使用getStaticProps

[英]NextJS: How to correctly use getStaticProps for firebase

我对 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 组件中。 任何帮助将不胜感激。

问题是您没有等待从get()返回的 promise 完成,因此返回一个空posts (您只在 promise 返回之后填充该变量,在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
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM