
想法
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>
);
}
// 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。处理不存在的页面
虚拟现实技术是仿真技术的一个重要方向,是仿真技术与计算机图形学人机接口技术多媒体技术传感技术网络技术等多种技术的集合,是一门富有挑战性的交叉技术前沿学科和研究领域。虚拟现实技术(VR)主要包括模拟环境、感知、自然技能和传感设备等方面。模拟环境是由计算机生成的、实时动态的三维立体逼真图像。感知是指理想的VR应该具有一切人所具有的感知。除计算机图形技术所生成的视觉感知外,还有听觉、触觉、力觉、运动等感
57
要处理 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号