开发者问题收集

Next JS + Contentful:无法获取用于获取 Contentful 数据的参数数据

2022-05-05
334

我想使用从 getStaticPaths 获取的 params 来获取 Contentful 中的数据。但是,我没有正确获取参数,因此我获取了错误的数据。

Argument of type 'string' is not assignable to parameter of type '{ slug: string; }'.

const getBlogEntries = async () => {
  const { items }: EntryCollection<IBlogFields> = await client.getEntries({
    content_type: "blog"
  })
  return items
}

const getBlogEntry = async ({ slug }: { slug: string }) => {
  console.log('slug', slug)
  
  const { items }: EntryCollection<IBlogFields> = await client.getEntries({
    content_type: "blog",
    "fields.slug[in]": slug,
    limit: 1
  })
  return items
}

export const getStaticPaths: GetStaticPaths = async () => {
  const items = await getBlogEntries()
  const paths = items.map((item) => {
    return {
      params: { slug: item.fields.slug },
    }
  })
  return {
    paths,
    fallback: false,
  }
}

export const getStaticProps: GetStaticProps = async ({
  params,
}) => {
  console.log('params', params!.slug)
  const items = await getBlogEntry(params!.slug as string)
  // the error occurs in `params!.slug`
  return {
    props: {
      blog: items[0],
    },
  }
}
1个回答

我得到了一个数据:

 const items = await getBlogEntry({ slug: params!.slug})
Shun Yamada
2022-05-05