【问题标题】:How to get slug value in getStaticProps to call api with parameter as slug如何在 getStaticProps 中获取 slug 值以调用 api,参数为 slug
【发布时间】:2021-09-09 03:07:25
【问题描述】:

页面内容:

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

【问题讨论】:

  • 上下文参数是一个对象,其中包含参数键,它将具有您的 slug 值,您可以使用该值进行 API 调用。我已经用代码发布了答案

标签: javascript next.js


【解决方案1】:

你可以在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 };
    }
}

【讨论】:

  • 当我添加它时它返回 服务器错误错误:getStaticPaths 是动态 SSG 页面所必需的,而“/gunluk/[...slug]”缺少。阅读更多:nextjs.org/docs/messages/invalid-getstaticpaths-value
  • 你能给getStaticPaths()举个例子吗
  • 我添加了 getStaticPath 示例供您参考
【解决方案2】:

我相信您正在寻找的是getStaticPaths

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 2022-11-06
    • 2020-10-22
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多