Nextjs:具有 API 集成的动态路由

nextjs:具有 api 集成的动态路由

想法

next.js 提供了一个基于文件的路由系统,支持动态路由(例如 /product/[id])。您可以将其与动态数据获取结合起来,创建灵活且可扩展的应用程序。这对于电子商务产品页面、用户个人资料或任何具有唯一标识符的内容等情况特别有用。

示例:动态产品页面

1。设置动态路线

在 /pages/product/ 等文件夹中创建一个名为 [id].tsx 的文件:

页面/产品/[id].tsx

2。获取动态路由的数据

// pages/product/[id].tsximport { getstaticpaths, getstaticprops } from 'next';type productprops = {  product: {    id: string;    name: string;    description: string;    price: number;  };};export default function productpage({ product }: productprops) {  return (    

{product.name}

{product.description}

price: ${product.price}

);}// generate dynamic paths for the product pagesexport 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 pageexport 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 集成的动态路由的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2648274.html

(0)
上一篇 2025年3月7日 08:08:58
下一篇 2025年3月7日 08:09:07

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论