Next.js 之 [id].tsx 实现动态路由(SSG)

738 阅读1分钟

实现根据id查看详情的功能

1. 添加Link标签

在需要跳转的位置添加Link标签

<Link href={`/posts/${item.id}`}>
  {item.title}
</Link>

如果页面中出现奇怪的404请求,可以尝试以下写法

<Link href="/posts/[id]" as={`/posts/${item.id}`}>
    {item.title}
</Link>

2. 创建文件

pages/posts/[id].tsx
没错,文件名就是[id].tsx

/pages/posts/id].tsx 的作用

  • 既声明了路由 /posts/:id
  • 又是 /posts/:id 的页面实现程序

3. 编辑 [id].tsx

i. 实现 getStaticPaths, 返回 id 列表

export const getStaticPaths:GetStaticPaths = async () => {
  const idList = await getPostIds()
  return {
    paths: idList.map(id => ({params: {id}})),
    fallback: false
  }
}

fallback: false 的作用

  • 是否自动兜底
  • false 表示如果请求的 id 不在 getStaticPaths 的结果里则直接返回 404 页面
  • true 表示自动兜底,id 找不到依然渲染页面

注意 id 不在结果里不代表 id 不存在,比如大型项目无法将所有产品页面都静态化,只静态化部分 id 对应的页面

ii. 实现 getStaticProps, 从第一个参数接收params.id

export const getStaticProps:GetStaticProps = async (x:any) => {
  const id = x.params.id
  const post = await getPost(id)
  return {
    props: { post }
  }
}

iii. 实现PostsShow组件,从 props 接收 post 数据

const postsShow: NextPage<Props> = (props) => {
  const {post} = props
  return (
    <div>
      <h1>{post.title}</h1>
      <article dangerouslySetInnerHTML={{__html: post.htmlContent}}/>
    </div>
  )
}
export default postsShow