Next.js动态路由如何使用

官方解释

Next.js 允许你创建具有 动态路由 的页面。例如,你可以创建一个名为 pages/posts/[id].js 的文件用以展示以 id 标识的单篇博客文章。当你访问 posts/1 路径时将展示 id: 1 的博客文章。

代码

这里先用一个写好的实例代码来展示

javascript 复制代码
import React from 'react';

// 步骤1
export async function getStaticPaths() {
    // 模拟调用外部 API 获取博文列表
    const posts = [
        { id: 1 },
        { id: 2 },
        { id: 3 }
    ];

    // 根据博文列表生成所有需要预渲染的路径
    const paths = posts.map((post) => ({
        params: { id: post.id.toString() }
    }));

    // 返回需要预渲染的路径和fallback配置
    return { paths, fallback: false };
}

// 步骤2
export async function getStaticProps({ params }) {
    // 使用params中的id获取特定博文数据,这里只是模拟数据
    const postData = { id: params.id, title: 'Post Title', content: 'Post Content' };

    return {
        props: {
            postData
        }
    };
}

// 渲染页面
function Post({ postData }) {
    return (
        <div>
            <h1>{postData.title}</h1>
            <h1>{postData.id}</h1>
            <p>{postData.content}</p>
        </div>
    );
}

export default Post;

我们依次访问一下路径
http://localhost:3000/post/1

http://localhost:3000/post/2

http://localhost:3000/post/3

不难发现每次渲染的都是不同页面,这就是动态路由,能够根据你传来的数字显示不同的页面

他和传统的动态路由不同,next.js的实现方式很简单:

下面是我这个页面的文件目录

可以看见我的文件名字是id.js,这个是next.js规定的

getStaticPaths 是给我们定义一个路径,也就是当我们访问http://localhost:3000/post/1的时候,文件中没有这个名字,但是也能访问的到

getStaticProps是用来给我们的页面传参的

function Post({ postData })中的postData是接收getStaticProps传来的参数

其余的都在上面的代码中,看一下很容易就能够理解运用起来

相关推荐
小小测试开发5 小时前
安装 Python 3.10+
开发语言·人工智能·python
KaMeidebaby6 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl6 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl7 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
AAA大运重卡何师傅(专跑国道)7 小时前
【无标题】
开发语言·c#
nuIl7 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl7 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf7 小时前
Python 异常处理
前端·后端·python
sugar__salt7 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
XBodhi.7 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio