【发布时间】: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