next.js 如何实现动态路由?

发布于:2025-04-22 ⋅ 阅读:(77) ⋅ 点赞:(0)

在 Next.js 12 中,动态路由和参数传递主要通过文件系统路由(File-system Routing)实现。以下是详细步骤和示例:

一、创建动态路由

  1. ‌文件命名规则‌

pages 目录下创建文件名用 [参数名].js 格式的文件,例如:

pages/posts/[id].js // 单个参数
pages/[category]/[id].js // 多段参数

  1. 匹配的 URL 示例‌
  • /posts/123id: '123'
  • /news/456category: 'news', id: '456'

二、传递参数

  1. 使用 <Link> 组件导航
import Link from 'next/link';

// 传递单个参数
<Link href="/posts/123">Post 123</Link>

// 传递多个参数(自动拼接 URL)
<Link href="/news/456?author=John">Post 456</Link>
  1. 编程式导航(useRouter
import { useRouter } from 'next/router';

function MyComponent() {
  const router = useRouter();

  const navigate = () => {
    // 传递单个参数
    router.push('/posts/123');
    
    // 传递多个参数(URL 自动拼接)
    router.push({
      pathname: '/news/[id]',
      query: { id: '456', author: 'John' },
    });
  };

  return <button onClick={navigate}>跳转</button>;
}

三、获取参数

  1. 在页面组件中获取参数
    使用 useRouterquery 对象:
import { useRouter } from 'next/router';

function Post() {
  const router = useRouter();
  const { id } = router.query; // 获取动态路由参数
  const { author } = router.query; // 获取查询参数(如 ?author=John)

  return <div>Post ID: {id}, Author: {author}</div>;
}
  1. getStaticPropsgetServerSideProps 中获取参数
    动态路由参数通过 context.params 传递:
export async function getStaticProps(context) {
  const { id } = context.params; // 获取动态路由参数
  const res = await fetch(`https://api.example.com/posts/${id}`);
  const post = await res.json();

  return { props: { post } };
}

// 必须定义 getStaticPaths 来生成静态页面
export async function getStaticPaths() {
  return {
    paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
    fallback: true, // 或 'blocking'
  };
}

四、高级用法

  1. 可选参数(Optional Parameters)
    使用双括号 [[...参数名]] 格式:
pages/posts/[[...slug]].js

匹配的 URL:

  • /postsslug: undefined
  • /posts/123slug: ['123']
  • /posts/123/456slug: ['123', '456']
  1. 捕获所有路径(Catch-all Routes)
    使用 [...参数名].js 格式:
pages/posts/[...slug].js

匹配的 URL:

  • /posts/123slug: ['123']
  • /posts/123/456slug: ['123', '456']

五、注意事项

  1. ‌fallback 模式‌

使用 getStaticPaths 时,若未预生成所有路径,需设置 fallback: true'blocking',并在页面处理加载状态。

  1. ‌客户端渲染与服务器渲染‌
  • 直接访问页面时(如刷新),参数会在首次渲染时存在。
  • 客户端导航时,参数可能稍后加载,需处理 router.isReady
useEffect(() => {
  if (router.isReady) {
    const { id } = router.query;
  }
}, [router.isReady]);
  1. 参数类型

所有参数均为字符串,需手动转换数字类型。

通过以上方法,你可以在 Next.js 12 中轻松实现动态路由、参数传递和获取。


网站公告

今日签到

点亮在社区的每一天
去签到