繁体   English   中英

如何在 getStaticProps 中获取 slug 值以使用参数作为 slug 调用 api

[英]How to get slug value in getStaticProps to call api with parameter as slug

页面内容:

import { useRouter } from "next/router";
    
export default function Gunluk({ data }) {
    let router = useRouter()
    
    const { slug } = router.query;
    return slug;
}

并在页面上显示 60d6180ea9284106a4fd8441(网址中的 https://.../gunluk/60d6180ea9284106a4fd8441 id)

所以我可以获得ID但我不知道如何将它传递给API。

export async function getStaticProps(context) {
    const res = await fetch(`http://localhost:3000/api/books-i-have`)
    const data = await res.json()
    
    if (!data) {
        return {
            notFound: true,
        }
    }
    
    return {
        props: { data }, // will be passed to the page component as props
    }
}

通常我使用它,但它在 slug 中不起作用。 我尝试了其他两种方法但都失败了( https://nextjs.org/docs/basic-features/data-fetching )。

简而言之,如何从 Slug 页面连接到 API?

文件目录:

    pages/
        gunluk/
            [...slug].js
            index.js

可以在 getStaticProps 中获取 slug 值,并使用它来调用基于 slug 的 api

export async function getStaticPaths() {
  const idList = await fetchAllIds();
  const paths = [
  ];
  idList.forEach((id) => {paths.push(`/gunluk/${id}`)})
  return { paths, fallback: true };
}

export async function getStaticProps({ params }) {
  const { slug } = params;

 try {
    const data= await fetchGunluk(slug);
    return data? { props: { data} } : { notFound: true };
  } catch (error) {
    console.error(error);
    return { notFound: true };
  }

}

我这样做了,我在 next.js 项目中有一个文件名pages/course/[course_slug].js

  const router = useRouter();
  const slug = router.query.course_slug;
  console.log(slug); //slug value

我相信你正在寻找的是getStaticPaths

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM