
想法
next.js 提供了一个基于文件的路由系统,支持动态路由(例如 /product/[id])。您可以将其与动态数据获取结合起来,创建灵活且可扩展的应用程序。这对于电子商务产品页面、用户个人资料或任何具有唯一标识符的内容等情况特别有用。
示例:动态产品页面
1。设置动态路线
在 /pages/product/ 等文件夹中创建一个名为 [id].tsx 的文件:
页面/产品/[id].tsx
2。获取动态路由的数据
// pages/product/[id].tsx
import { getstaticpaths, getstaticprops } from 'next';
type productprops = {
product: {
id: string;
name: string;
description: string;
price: number;
};
};
export default function productpage({ product }: productprops) {
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<p>price: ${product.price}</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/xiazai/code/10723">
<img src="https://img.php.cn/upload/webcode/000/000/011/176345100329973.jpg" alt="奥硕企业网站管理系统3.0.2">
</a>
<div class="aritcle_card_info">
<a href="/xiazai/code/10723">奥硕企业网站管理系统3.0.2</a>
<p>临沂奥硕软件有限公司拥有国内一流的企业网站管理系统,奥硕企业网站管理系统真正会打字就会建站的管理系统,其强大的扩展性可以满足企业网站实现各种功能(唯一集成3O多套模版的企业建站系统)奥硕企业网站管理系统具有一下特色功能1、双语双模(中英文采用单独模板设计,可制作中英文不同样式的网站)2、在线编辑JS动态菜单支持下拉效果,同时生成中文,英文,静态3个JS菜单3、在线制作并调用FLASH展示动画4、自</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="奥硕企业网站管理系统3.0.2">
<span>0</span>
</div>
</div>
<a href="/xiazai/code/10723" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="奥硕企业网站管理系统3.0.2">
</a>
</div>
</div>
);
}
// generate dynamic paths for the product pages
export const getstaticpaths: getstaticpaths = async () => {
const res = await fetch('https://api.example.com/products');
const products = await res.json();
// map over the products to define paths
const paths = products.map((product: { id: string }) => ({
params: { id: product.id },
}));
return {
paths, // pre-render these paths at build time
fallback: 'blocking', // dynamically render other pages on request
};
};
// fetch product data for each page
export const getstaticprops: getstaticprops = async ({ params }) => {
const res = await fetch(`https://api.example.com/products/${params?.id}`);
const product = await res.json();
// pass the product data as props
return {
props: { product },
revalidate: 10, // revalidate every 10 seconds
};
};
3。处理不存在的页面
要处理 id 不存在的情况,请在 getstaticprops 中返回 notfound 属性:
export const getStaticProps: GetStaticProps = async ({ params }) => {
const res = await fetch(`https://api.example.com/products/${params?.id}`);
if (res.status === 404) {
return { notFound: true };
}
const product = await res.json();
return {
props: { product },
revalidate: 10,
};
};
此方法的主要特点:
seo 友好:页面使用完整的 html 进行预渲染,非常适合搜索引擎。
可扩展:您可以使用回退渲染(fallback:'blocking')为新数据动态生成页面。
实时更新:与重新验证相结合,确保数据保持最新,无需手动部署。
错误处理:使用 notfound 优雅地处理 404 或其他错误。
此方法允许您构建高度动态且响应迅速且易于扩展的 web 应用程序!
以上就是Nextjs:具有 API 集成的动态路由的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号