【问题标题】:Data fetched from getStaticProps is not displayed in page component从 getStaticProps 获取的数据不显示在页面组件中
【发布时间】:2021-05-11 00:22:28
【问题描述】:

我是 Next.js 的新手,我正在尝试使用带有 firebase 的 getStaticPathsgetStaticProps 获取详细信息页面。

import firebase from '../../firebase'

export const getStaticPaths = async () => {
  let posts = []
  const ref = firebase.firestore().collection('posts')
  try {
    let allPosts = await ref.get()
    for (const doc of allPosts.docs) {
      console.log(doc.id, '=>', doc.data())
      console.log('the id is....')

      let data = doc.data()
      console.log(data.ytid)
      posts.push({
        title: data.title,
        ytid: data.ytid,
      })
    }
  } catch (e) {
    console.log(e)
  }
  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.ytid },
  }))

  return { paths, fallback: false }
}

export const getStaticProps = async (context) => {
  const id = context.params.id

  console.log('id is')
  console.log(id)

  let post = []

  try {
    const ref = firebase.firestore().collection('posts').where('ytid', '==', id)

    const qsnapshot = await ref.get()
    qsnapshot.forEach((doc) => {
      const data = doc.data()
      console.log('the title is...')
      console.log(data.title)
      post.title = data.title
      post.ytid = data.ytid
    })
    return {
      props: { post: post },
      revalidate: 1,
    }
  } catch (e) {
    console.log(e)
  }
}

const Details = ({ post }) => {
  console.log('posting...')
  console.log(post.title)
  return (
    <div>
      <div className='mx-auto'>
        <h2>Post Details Page</h2>
        <h3 className='text-black'>{post.title}</h3>
        <h4>Details here</h4>
      </div>
    </div>
  )
}

export default Details

不知何故,post.title 没有显示在详细信息页面的 h3 标记中,但是当我查看控制台终端时,它会打印在那里。所以它显示在后端而不是前端。不太确定它是否是由某些配置问题引起的,我们将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    在您的getStaticProps 函数中,您初始化了let post = [](我假设错了?),即使您可以将属性添加到数组(它是一个对象),当数组转换为 JSON 时属性会被忽略.

    在构建时预渲染带有 getStaticProps 的页面时,除了页面 HTML 文件之外,Next.js 还会生成一个 JSON 文件,其中包含运行 getStaticProps 的结果。 doc

    let post = [] 更改为let post = {},它应该可以正常工作。

    【讨论】:

    • 如果我们有 1000 个帖子,我们应该在每次重新加载时加载所有 1000 个帖子吗?
    • @JoelJerushan getStaticProps 在构建时在服务器上运行一次以预渲染页面。它不会在对页面的每个请求上运行。
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2020-05-20
    相关资源
    最近更新 更多