getStaticPaths 是在没有 getStaticProps 的情况下添加的 - 打字稿

getStaticPaths was added without a getStaticProps - typescript

我正在使用 nextJS、typescript 和 sanity CMS 创建博客。我创建了 post 完美显示的主页。接下来,当我点击 post 时,我将获取博客 post 的详细信息。当我在 sanity dashboard here 中调用它时,这个查询可以完美地获取数据

这是 Post 打字

export interface Post {
  _id: string
  _createdAt: string
  title: string
  author: {
    name: string
    image: string
  }
  description: string
  mainImage: {
    asset: {
      url: string
    }
  }
  slug: {
    current: string
  }
  body: [object]
}

[鼻涕虫].tsx:

import { GetStaticProps } from 'next'
import Header from '../../components/Header'
import { sanityClient, urlFor } from '../../sanity'
import { Post } from '../../typings'

interface Props {
  post: Post
}
function Post({ post }: Props) {
  //   console.log(post)
  return (
    <main>
      <Header />
      {/* <img src={urlFor(post.mainImage).url()} alt="" /> */}
    </main>
  )
}

export default Post
export const getStaticPaths = async () => {
  const query = `*[_type == "post"]{
        _id,
        slug{
            current
        }
    }`
  const posts = await sanityClient.fetch(query)
  const paths = posts.map((post: Post) => ({
    params: {
      slug: post.slug.current,
    },
  }))

  return {
    paths,
    fallback: 'blocking',
  }
}
export const GetStaticProps: GetStaticProps = async ({ params }) => {
  const query = `*[_type == "post" && slug.current == $slug][0]{
  _id,
  _createdAt,
  title,
  author-> {
  name,
  image
},
 description,
 mainImage,
 slug,
 body
}`
  const post = await sanityClient.fetch(query, {
    slug: params?.slug,
  })

  if (!post) {
    return {
      notFound: true,
    }
  }
  return {
    props: {
      post,
    },
    revalidate: 60,
  }
}

我得到的错误是:

Error: getStaticPaths was added without a getStaticProps in /post/[slug]. 
Without getStaticProps, getStaticPaths does nothing

你的问题是你 getStaticProps 定义错误。如果你注意到你的定义是GetStaticProps(首字母大写)而不是getStaticProps(Next.js生命周期的函数)

修复只需修改为getStaticProps: GetStaticProps

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const query = `*[_type == "post" && slug.current == $slug][0]{
  _id,
  _createdAt,
  title,
  author-> {
  name,
  image
},
 description,
 mainImage,
 slug,
 body
}`
  const post = await sanityClient.fetch(query, {
    slug: params?.slug,
  })

  if (!post) {
    return {
      notFound: true,
    }
  }
  return {
    props: {
      post,
    },
    revalidate: 60,
  }
}