【问题标题】:getStaticPaths is required for dynamic SSG pages and is missing for '/contentslug/[slug]'动态 SSG 页面需要 getStaticPaths,而“/contentslug/[slug]”则缺少 getStaticPaths
【发布时间】:2022-01-16 21:25:38
【问题描述】:

我遇到了一个错误,我不知道为什么?在我的页面目录中,我有一个名为 contentslug 的文件夹,其中包含 [slug.js]

我正在关注本教程 - https://www.youtube.com/watch?v=Mdx3ywlnzk8

这是slug.js中的代码

import Image from  'next/image'
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';
  
export default function BlogPosts({ posts}) {

    const {featuredImage, title , information } = posts.fields

    return (
        <div>
        <div>
            <Image
                src={'https:' + featuredImage.fields.file.url}
                width={featuredImage.fields.file.details.image.width}
                height={featuredImage.fields.file.details.image.height}
            />
        </div>
        <div>
            {documentToReactComponents(information)}
        </div>
        </div>
    )
}
  
export async function getStaticProps({params}) {
    const {items} = await client.getEntries({
        content_type: 'posts',
        'fields.slug': params.slug
    })

    return {
        props: {posts: items[0], fallback: 'blocking'}
    }
}

这是链接到它的组件

import Link from 'next/link'

export default function BlogPosts({post }) {
   
   const {title, information, slug, thumbnail} = post.fields
   
   return (
        <div className="container text-center ">
            <div>
                <div>
                    <h4 className=''>{title}</h4>
                    <Link href={'/contentslug/' + slug}>
                        <a className='btn btn-primary text-white'>Read more</a>
                    </Link>
                </div>
            </div>
    )
}
        

有什么想法吗?

【问题讨论】:

    标签: javascript next.js contentful


    【解决方案1】:

    如果您正在学习本教程并且您在链接的第 5 集中,那么您不应该编辑 [slug] 页面,它只会发生在第 7 集中 https://www.youtube.com/watch?v=DRF1KBTH15k&list=PL4cUxeGkcC9jClk8wl1yJcN3Zlrr8YSA1&index=7

    但如果您已经想处理该页面,则需要添加 getStaticPaths 函数来生成 getStaticProps 将获得的路径:

    export const getStaticPaths = async () => {
      const res = await client.getEntries({ 
        content_type: "recipe" 
      })
    
      const paths = res.items.map(item => {
        return {
          params: { slug: item.fields.slug }
        }
      })
    
      return {
        paths,
        fallback: false
      }
    }
    

    【讨论】:

    • 实际上蛞蝓在此之前就起作用了,这就是我遇到问题的原因。我在上面添加了您的代码,它抛出的客户端未定义为错误。那么,我如何将上面的代码适合我的呢?
    • 我做到了 7,这就是我注意到这个错误的地方。一开始他点击“煮这个”链接并直接进入蛞蝓,但对我来说,我得到了上述错误。
    • 你试过在 Github 上查看课程代码吗? github.com/iamshaunjp/next-contentful/blob/lesson-7/pages/… 比如这个是第7课的,同一个文件
    • 是的,我错过了一些东西!谢谢:)
    猜你喜欢
    • 2021-04-23
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2021-03-30
    • 2021-01-29
    • 2021-07-22
    相关资源
    最近更新 更多