【问题标题】:Property 'slug' does not exist on type 'ParsedUrlQuery | undefined''ParsedUrlQuery | 类型不存在属性'slug'不明确的'
【发布时间】:2021-10-28 00:29:48
【问题描述】:

我试图在getServerSideProps 上获取我的页面的路径,但params 的类型是object

我需要做什么才能得到字符串?

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { slug } = context.params // Property 'slug' does not exist on type 'ParsedUrlQuery | undefined'.ts(2339)

  return {
    props: {
    },
  }
}

【问题讨论】:

    标签: javascript typescript next.js


    【解决方案1】:

    如果您正在寻找字符串形式的路径,您可以尝试context.req.url。 (请参阅docs 了解context 属性的完整列表)。

    对于动态参数,它取决于您为页面命名的内容,例如,如果您有一个博客文章页面,其中包含 pages/posts/[post].js 文件,则 slug 将位于 context.params.post 中,而不是 context.params.slug .

    希望对您有所帮助!

    【讨论】:

    • 它的参数是slug([slug].tsx),但是如何输入呢?我收到错误:“ParsedUrlQuery | 类型”上不存在属性“slug”未定义'
    • const slug = context.params?.slug as string 正确吗?
    • 哦,有趣!我想知道为什么它似乎将context.params 解释为类型ParsedUrlQuery ?
    • 我不肯定这是同一个问题,但也许尝试将它呈现为这个问题的答案here
    • 还有here's 另一个帖子,其中包含有关可能是什么问题的一些信息以及建议的解决方案。
    猜你喜欢
    • 2020-03-06
    • 2019-06-26
    • 1970-01-01
    • 2021-06-16
    • 2018-11-23
    • 2021-04-12
    • 2021-12-20
    • 2017-12-31
    • 2017-06-06
    相关资源
    最近更新 更多