【问题标题】:Dynamic routing in Next.js gets TypeError: the ‘id’ argument must of type ‘string’. Received nullNext.js 中的动态路由获取 TypeError:“id”参数必须是“字符串”类型。收到空
【发布时间】:2020-12-16 23:37:53
【问题描述】:

我在 Next.js 中生成动态页面时遇到了问题。我正在从 Sanity 中提取数据,我认为我的代码是正确的,但每次我尝试加载页面时都会收到类型错误 - “‘id’参数必须是字符串类型。收到无效”。文件路径是‘/post/[slug].js’,所以这是我自始至终使用的变量名 - 我不确定 id 来自哪里,或者它是否是我需要传递的额外内容,或者我没有传递我的 slug 正确!

我在 Sanity 论坛上询问过,这似乎不是 API 问题 - 我能够毫无问题地从应用程序的其他部分提取数据。在控制台中,页面似乎编译成功,但在尝试加载时出现此错误。我已经在页面组件中使用空 div 进行了尝试,以确保它在表示逻辑中没有任何内容,但没有运气。

我已将完整的错误消息放在 gist 中,它看起来像是带有 jest 或 next-server 的东西。对于我的生活,我无法弄清楚!

import client from '../../client’

const Post = ({ post }) => {
  ...
}

export default Post

export const getStaticPaths = async () => {
  const posts = await client.fetch(`*[_type == "blog"]{ slug }`)
  const paths = posts.map(post => ({
    params: {
      slug: post.slug.current
    }
  }))
  
  return { 
    paths,
    fallback: false }
}

export const getStaticProps = async ({ params }) => {
  const post = await client.fetch(`*[_type == "blog" && slug.current == $slug]{ title, date, link, excerpt, body, slug }[0]`, {slug: params.slug})
  
  return {
    props: { post }
  }
} 

更新:这似乎是 play.js 或其使用的配置的问题 - 在桌面环境中尝试不会导致相同的错误。

【问题讨论】:

    标签: javascript next.js sanity


    【解决方案1】:

    我认为问题在于您的文件名。名称只能是[slug].js,它应该位于pages/post。当您通过 URL http://localhost:xxx/post/pulled-sanity-slug 访问页面时,它应该可以正常工作

    【讨论】:

    • 谢谢!抱歉,我不清楚 - 这是整个路径,文件本身只是 [slug].js
    猜你喜欢
    • 2022-09-27
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 2021-09-08
    • 2020-12-30
    • 2020-08-12
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多