首页 > web前端 > js教程 > 正文

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

心靈之曲
发布: 2024-11-27 22:24:01
转载
567人浏览过

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,
  };
};
登录后复制

此方法的主要特点:

  1. seo 友好:页面使用完整的 html 进行预渲染,非常适合搜索引擎。

  2. 可扩展:您可以使用回退渲染(fallback:'blocking')为新数据动态生成页面。

  3. 实时更新:与重新验证相结合,确保数据保持最新,无需手动部署。

  4. 错误处理:使用 notfound 优雅地处理 404 或其他错误。

此方法允许您构建高度动态且响应迅速且易于扩展的 web 应用程序!

以上就是Nextjs:具有 API 集成的动态路由的详细内容,更多请关注php中文网其它相关文章!

路由优化大师
路由优化大师

路由优化大师是一款及简单的路由器设置管理软件,其主要功能是一键设置优化路由、屏广告、防蹭网、路由器全面检测及高级设置等,有需要的小伙伴快来保存下载体验吧!

下载
相关标签:
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号