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 分钟
难度级别: 初级 🟢

相关推荐
切糕师学AI15 小时前
深入解析前端页面在 Safari 与 Chrome 浏览器中的差异及解决方案
前端·chrome·safari
fengtangjiang15 小时前
tomcat和国产web中间件区别和联系
前端·中间件·tomcat
ahauedu15 小时前
本地部署开源的前端项目npm经历(1)
前端·npm·开源
h_654321015 小时前
打包报错ERROR Error: Cannot find module ‘webpack/lib/RuleSet‘
前端·webpack·npm
小旋风0123415 小时前
uniapp开发app解决视频层级太高的问题(subNvue方法)
前端·uni-app·音视频
Jinuss16 小时前
源码分析之React中useCallback和useMemo
前端·javascript·react.js
maxmaxma16 小时前
ROS2机器人少年创客营:Python第一课
前端·python·机器人
吃西瓜的年年16 小时前
react(二)useEffect 和 useRef
前端·react.js·前端框架
RDCJM16 小时前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
LZQ <=小氣鬼=>16 小时前
React 插槽(Slot)
前端·javascript·react.js