当前位置: 首页 > news >正文

Next.js - 03 - 路由详解

Next.js 路由跳转

三者对比

API场景
<Link href="...">默认首选,声明式站内链接
redirect('/path')Server Component / Server Action 里,服务端直接跳转
useRouter().push()客户端逻辑触发,如表单提交成功后、定时跳转、按钮回调

1. 声明式跳转(最常用)

<Link>组件,适合菜单、按钮、列表项等可点击链接。

基本用法

import Link from "next/link"; <Link href="/about">关于我们</Link>;

带动态路由参数

对应文件app/posts/[slug]/page.tsx(App Router 动态段直接写进路径字符串):

const slug = 'hello-world' <Link href={`/posts/${slug}`}>文章详情</Link> <Link href={`/tags/${tagName}`}>标签页</Link>

带查询参数(Query String)

// 字符串写法(最直观) <Link href="/search?q=nextjs&page=2">搜索 Next.js</Link> // URLSearchParams(参数多、需编码时更安全) const params = new URLSearchParams({ q: 'nextjs', page: '2' }) <Link href={`/search?${params.toString()}`}>搜索 Next.js</Link> // 对象写法(仅固定 pathname + query,不含 [slug] 动态段) <Link href={{ pathname: '/search', query: { q: 'nextjs', page: '2' } }}> 搜索 Next.js </Link>

特点

  • 客户端路由,不整页刷新
  • 会预取(prefetch)目标页面,体验更好
  • SEO 友好(本质是<a>

2. 编程式跳转(代码里跳转)

在事件处理、登录成功后、表单提交后等场景使用。

基本用法

"use client"; import { useRouter } from "next/navigation"; const router = useRouter(); router.push("/dashboard"); // 跳转,可回退 router.replace("/login"); // 替换当前历史记录,不能回退到上一页 router.back(); // 返回 router.forward(); // 前进 router.refresh(); // 仅 App Router,URL 不变、不整页刷新,但让当前路由的 Server Component 重新跑一遍,拿到最新服务端数据。

和 push / 浏览器刷新的区别

操作URL 变吗整页刷新吗服务端组件重跑吗
router.push(‘/other’)✅ 变❌(客户端路由)✅ 新页面
router.refresh()❌ 不变✅ 当前页
浏览器 F5❌ 不变✅ 整页重载✅ 且客户端状态全丢

典型场景

'use client' async function handleSubmit() { await updateProfile(formData) // 后端数据已更新 router.refresh() // 当前页重新拉服务端数据,UI 更新 // 不需要 router.push('/profile'),因为本来就在 profile 页 }

带动态路由参数

App Router 的router.push只接受字符串

const slug = "hello-world"; router.push(`/posts/${slug}`); router.replace(`/tags/${tagName}`);

带查询参数

// 字符串写法 router.push("/search?q=nextjs&page=2"); // URLSearchParams const params = new URLSearchParams({ q: "nextjs", page: "2", sort: "date" }); router.push(`/search?${params.toString()}`); // 在当前页追加/修改 query(保留其他参数,需配合 usePathname / useSearchParams) import { usePathname, useSearchParams } from "next/navigation"; const pathname = usePathname(); const searchParams = useSearchParams(); const next = new URLSearchParams(searchParams.toString()); next.set("page", "3"); router.push(`${pathname}?${next.toString()}`);

常见方法

方法作用
push跳转到新页面,保留历史
replace跳转并替换当前页,不能回退到上一页
back/forward浏览器历史前进后退
refresh仅 App Router,重新获取服务端数据

3. 服务端跳转(不经过客户端 JS)

适合权限校验、旧 URL 重定向、国际化路由等。

基本用法

import { redirect } from "next/navigation"; // Server Component / Server Action 中 redirect("/login");

带参数跳转

// 动态路由 redirect(`/posts/${slug}`); // 查询参数 redirect(`/search?q=${encodeURIComponent(keyword)}&page=1`);

其他方式

  • middleware.ts里做条件重定向
  • notFound()跳转到 404 页(严格说是「展示 404」,不是普通跳转)

调用 notFound() 时:

  • URL 不会变成 /404,地址栏仍是 /posts/404-test
  • Next.js 内部抛一个特殊的 NOT_FOUND 信号
  • 渲染最近一层的 not-found.tsx

同类约定:error.tsxloading.tsx也是按路由段就近渲染且 URL 不变,但触发方式不同——前者是运行时错误,后者是 Suspense 加载。


4. 跳转后如何获取参数

跳转时传的参数分两类:动态路由段/posts/[slug])和查询参数?q=xxx)。

服务端(Server Component)

页面组件通过 props 接收:

// app/posts/[slug]/page.tsx interface Props { params: Promise<{ slug: string }>; searchParams: Promise<{ q?: string; page?: string }>; } export default async function Page({ params, searchParams }: Props) { const { slug } = await params; // 动态段:/posts/hello → slug = 'hello' const { q, page } = await searchParams; // 查询串:?q=nextjs&page=2 // ... }

Server Action 里可从formData或函数参数读取,再redirect到带参 URL。

客户端(Client Component)

"use client"; import { useParams, useSearchParams } from "next/navigation"; export default function SearchBar() { const params = useParams(); // { slug: 'hello' } const searchParams = useSearchParams(); const slug = params.slug as string; const q = searchParams.get("q"); // 'nextjs' 或 null const page = searchParams.get("page") ?? "1"; // ... }

useSearchParams()会使组件在客户端渲染;若只需在服务端读 query,优先用 Server Component 的searchParamsprop。

参数类型对照

参数来源URL 示例跳转写法读取方式(服务端)读取方式(客户端)
动态路由段/posts/hello`/posts/${slug}`(await params).sluguseParams().slug
查询参数/search?q=nextjs`/search?${params}`URLSearchParams(await searchParams).quseSearchParams().get('q')
多段动态路由/tags/react`/tags/${name}`(await params).sluguseParams().slug

速记

  1. 能点链接就用<Link>,SEO 和预取都更好。
  2. 事件里跳转用router.push/replace,记得'use client'
  3. 权限/校验在服务端用redirect,不暴露客户端逻辑。
  4. 动态段用params,查询串用searchParams;客户端对应useParams/useSearchParams
http://www.jsqmd.com/news/1153378/

相关文章:

  • 计算机毕业设计之冷冻食品仓储管理信息系统
  • 大模型推理 Accuracy Regression 检测——当快了可能意味着错了
  • 分布式ID生成方案在创业项目中的选型:雪花算法与号段模式对比
  • 终极指南:3步解决Windows程序运行依赖问题
  • 企业级JetBrains IDE评估重置架构解决方案
  • ESLint 自定义规则实战:用 AST 分析封堵团队特有的代码坏味道
  • 永康智能锁厂家直销
  • STM32与MCP3202实现锂电池主动均衡系统设计
  • InfluxDB 完全指南:时序数据库的标杆之作
  • Session Cookie 影响登录态怎么排查?Profile、LocalStorage 和任务边界一起看
  • LLM 提示词版本管理:像管理数据库迁移一样管理你的 Prompt 演进
  • pandas 内存优化:read_csv 的 dtype 参数能省一半内存
  • AI智能体Codex外贸客户开发实战:从模糊意图到精准客户名单的自动化挖掘
  • PostgreSQL 分区表实战——从大表查询 43 秒到 0.3 秒的分区策略迁移
  • Ice:macOS菜单栏管理技术方案与架构深度解析
  • 机器学习入门:10小时掌握四大核心算法与Python实战
  • Llama 3.1 128K 长文本处理:语义滑动窗口 vs. 位置插值外推实测
  • SAP IBP 2024 供应链规划实战:从业务顾问视角配置 3 个核心预测模型
  • 2026年程序员必看:如何谈出高薪Offer?收藏!
  • Cesium(三)添加标记点、绘制线并清除,添加wms影像底图
  • ACOLITE开源卫星大气校正工具:5大核心技术深度解析与多传感器应用指南
  • MyComputerManager终极指南:如何彻底清理Windows“此电脑“中的顽固图标
  • 目录 全书章节总目《程序员自进化与Agent Harness工程》
  • 【审计专栏】【管理科学】【社会科学】第六十九篇 人的心机和算计模型列表05 人性驱动组织——欲望、恐惧、认同、归属、傲慢、懒惰01
  • PCB 叠构设计避坑:Core与PP选型3大误区及10层板阻抗偏差实测
  • JavaWeb 内存马实战排查:Arthas 5大命令定位 Filter/Servlet 型后门
  • 新人AI产品经理成长指南
  • 主权AI与税收红利:韩国如何构建自主可控的人工智能生态
  • 手把手教你用LangChain搭建企业级RAG问答系统,解决大模型知识幻觉难题
  • 桌面版炼丹炉,开箱即训!零环境配置 · 图形化训练 · 自动打标 · 实时监控——无需折腾,专注素材与效果。