【问题标题】:How can I use dynamic routes in nexy.js typescipt如何在 next.js 打字稿中使用动态路由
【发布时间】:2021-05-23 08:12:11
【问题描述】:

我有这个文件夹结构

[postId].ts

import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  const { pid } = router.query

  return <p>Post: {pid}</p>
}

export default Post

我收到这个错误,不知道如何解决,谁能告诉我如何解决?

更新:

也许问题出在我的 tsconfig.json 中

 {
  "compilerOptions": {
    "target": "esnext",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

【问题讨论】:

  • 如果您暂时删除{pid} 会怎样?顺便说一句,你应该使用const { postId } = router.query
  • @SomeoneSpecial 没什么,我可以只留下一段文字,但它仍然不起作用
  • 您按照 nextJS 的说明设置了 typescript?你显示的代码,至少没有错(除了我上面提到的)
  • @SomeoneSpecial 是的,我关注了 nextjs 文档
  • @SomeoneSpecial 它可能必须与打字稿有关

标签: reactjs typescript next.js


【解决方案1】:

你的文件名是[postId],所以应该是你的参数名:

const { postId } = router.query
【解决方案2】:

你的文件名应该是 jsx / tsx 类型所以

而不是

[postId].ts

应该是

[postId].tsx

【讨论】:

    【解决方案3】:

    我刚从 webstorm 转到 vscode,一切正常,可能是我的 tsconfig 文件有问题

    【讨论】:

      猜你喜欢
      • 2022-07-31
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-05
      • 2022-11-12
      • 2020-10-11
      • 2022-11-12
      相关资源
      最近更新 更多