Nextjs:具有 API 集成的动态路由
收藏
各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题是《Nextjs:具有 API 集成的动态路由》,很明显是关于文章的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

想法
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。处理不存在的页面
要处理 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 集成的动态路由》的内容介绍就到此结束,如果有什么疑问或者建议,可以在米云公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
版本声明 本文转载于:dev.to 如有侵犯,请联系删除
- 如何将数组中对象的键名替换为另一个数组提供的键名?
