Next.js 动态路由
在 Next.js 中,我们可以动态创建路由。在此示例中,我们将动态创建页面及其路由。
步骤 1. 定义 [id].js 文件-[id].js 表示动态页面,其中 id 将是相对路径。在 pages/post 目录中定义此文件。
步骤 2. 定义 lib/posts.js-posts.js 表示 id 和内容。 lib目录要在根目录下创建。
[id].js
使用设置路径的 getStaticPaths() 方法和根据 id 获取内容的 getStaticProps() 方法更新 [id].js 文件。
import Link from 'next/link'
import Head from 'next/head'
import Container from '../../components/container'
import { getAllPostIds, getPostData } from '../../lib/posts'
export default function Post({ postData }) {
return (
<Container>
{postData.id}
<br />
{postData.title}
<br />
{postData.date}
</Container>
)
}
export async function getStaticPaths() {
const paths = getAllPostIds()
return {
paths,
fallback: false
}
}
export async function getStaticProps({ params }) {
const postData = getPostData(params.id)
return {
props: {
postData
}
}
}
posts.js
posts.js 包含 getAllPostIds() 获取 id 和 getPostData() 获取相应内容。
export function getPostData(id) {
const postOne = {
title: 'One',
id: 1,
date: '7/12/2020'
}
const postTwo = {
title: 'Two',
id: 2,
date: '7/12/2020'
}
if(id == 'one'){
return postOne;
}else if(id == 'two'){
return postTwo;
}
}
export function getAllPostIds() {
return [{
params: {
id: 'one'
}
},
{
params: {
id: 'two'
}
}
];
}
启动 Next.js 服务器
运行以下命令启动服务器-。
npm run dev
> nextjs@1.0.0 dev \Node\nextjs
> next
ready-started server on http://localhost:3000
event-compiled successfully
event-build page: /
wait -compiling...
event-compiled successfully
event-build page: /next/dist/pages/_error
wait -compiling...
event-compiled successfully
验证输出
在浏览器中打开 localhost:3000/posts/one,您将看到以下输出。
在浏览器中打开 localhost:3000/posts/two ,您将看到以下输出。
