Next.js第四章(路由导航)

路由导航

路由导航是指我们在Next.js中跳转页面的方式,例如原始的<a>标签,等。

在Next.js中,共有四种方式提供跳转:

  • Link组件
  • useRouter Hook (客户端组件)
  • redirect函数 (服务端组件)
  • History API (浏览器API 本文略过用的不多 了解即可)

Link组件

<Link>是一个内置组件,在a标签的基础上扩展了功能,并且还能用来实现预获取(prefetching),以及保持滚动位置(scroll)等。

基本用法

tsx 复制代码
import Link from "next/link" //引入Link组件
export default function Home() {
    return (
        <div>
            <Link href="/about">跳转About页面</Link>
            <Link href={{pathname: "/about", query: {name: "张三"}}}>跳转About并且传入参数</Link>
            <Link href="/page" prefetch={true}>预获取page页面</Link>
            <Link href="/xm" scroll={true}>保持滚动位置</Link>
            <Link href="/daman" replace={true}>替换当前页面</Link>
        </div>
    )
}

支持动态渲染

tsx 复制代码
import Link from "next/link"
export default function Page() {
    const arr = [1, 2, 3, 4, 5]
    return arr.map((item) => (
        <Link key={item} href={`/page/${item}`}>动态渲染的Link</Link>
    ))
}

useRouter Hook

useRouter 可以在代码中根据逻辑跳转页面,例如根据用户权限跳转不同的页面。

使用该hook需要在客户端组件中。需要在顶层编写 'use client' 声明这是客户端组件。

tsx 复制代码
'use client'
import { useRouter } from "next/navigation"
export default function Page() {
    const router = useRouter()
    return (
        <>
        <button onClick={() => router.push("/page")}>跳转page页面</button>
        <button onClick={() => router.replace("/page")}>替换当前页面</button>
        <button onClick={() => router.back()}>返回上一页</button>
        <button onClick={() => router.forward()}>跳转下一页</button>
        <button onClick={() => router.refresh()}>刷新当前页面</button>
        <button onClick={() => router.prefetch("/about")}>预获取about页面</button>
        </>
    )
}

redirect 函数

redirect 函数可以用于服务端组件/客户端组件中跳转页面,例如根据用户权限跳转不同的页面。

在Next.js中 redirect的状态是:307临时重定向

tsx 复制代码
import { redirect } from "next/navigation"
export default async function Page() {
   const checkLogin = await checkLogin()
   //如果用户未登录,则跳转到登录页面
   if (!checkLogin) {
    redirect("/login")
   }
   return (
    <div>
        <h1>Page</h1>
    </div>
   )
}

permanentRedirect 函数

permanentRedirect 跟上面的redirect的区别是:permanentRedirect是永久重定向,而redirect是临时重定向。

在Next.js中 permanentRedirect的状态是:308永久重定向

tsx 复制代码
//用法跟redirect一样,只是状态码不同
import { permanentRedirect } from "next/navigation"
export default async function Page() {
   const checkLogin = await checkLogin()
   if (!checkLogin) {
    permanentRedirect("/login")
   }
}

permanentRedirect / redirect 注意事项

  • path 字符串类型,表示重定向的 URL,可以是相对路径,也可以是绝对路径
  • type 值为 replace (默认)或者 push(Server Actions 中默认),表示重定向的类型

permanentRedirectredirect 在 Sever Actions 中会用 push添加到浏览器历史,在其他地方用 replace在浏览器历史栈中替换当前的 URL。你可以通过指定 type参数覆盖此行为。

注意:在服务端组件中使用 type参数没有效果。

预计学习时间 : 5 分钟
难度级别: 初级 🟢

相关推荐
七牛开发者3 分钟前
Coding Agent 如何跑稳长任务?从上下文管理到运行时状态
前端·javascript·后端
半个落月15 分钟前
从 CSR 到 Server Component:吃透 Next.js 16 App Router 路由、布局与 SEO
前端·next.js
七牛开发者21 分钟前
拆解 DeepSeek Harness:Profile 与 Bundle 如何装配运行时
前端·javascript·后端
葡萄城技术团队27 分钟前
表格智能体系列 · 1:一句话怎么变成一次表格操作
前端
梦曦i34 分钟前
Vue-Router 2.4.0 新增可控重定向功能
前端·uni-app
deli0070071 小时前
Markdown 实时预览器:左边写右边看,排版效率翻倍
前端·ai编程
郑州光合科技余经理1 小时前
海外版外卖系统架构:订单怎么流转、权限怎么分
java·开发语言·前端·系统架构·uni-app·php·ai编程
pengyu1 小时前
【Kotlin 协程修仙录 · 炼虚境 · 初阶】 | 虚空造物:Channel 基础与协程间通信的管道艺术
android·前端·kotlin
提线木偶1 小时前
CORS 到底谁说了算?一份跨域配置的避坑指南
前端·后端
网安蟹佬霸2 小时前
区块链与智能合约安全实战:从Solidity审计到DeFi漏洞深度剖析
运维·前端·网络·安全·自动化·区块链·智能合约