【发布时间】:2021-05-03 00:29:03
【问题描述】:
我正在尝试在我的 Next.js 应用程序中使用包含多个数组的 json 文件。我的 json 文件有点复杂,所以我不确定如何将其转换为 getStaticPaths 函数可用的对象。我收到以下错误消息:
Error: A required parameter (id) was not provided as a string in getStaticPaths for /planets/[id]
这是我的 [id].js 文件的代码:
import { useRouter } from 'next/router'
import Head from 'next/head'
export default function Planet({ planet }) {
const router = useRouter()
const { id } = router.query
return (<>
<Head>
<title>{planet.name}</title>
</Head>
<h1>Hello {id}</h1>
<h2>HHHHHHH</h2>
</>)
}
export async function getStaticPaths() {
const json = await import('https://api.jsonbin.io/b/600c5ab8bca934583e40b908').default;
const bodies = await json.json()
const paths = bodies.planets.map(planet => ({
params: { id: planet.id.toString() },
}));
return {
paths,
fallback: false
}
}
export async function getStaticProps({params}) {
const json = await import('https://api.jsonbin.io/b/600c5ab8bca934583e40b908').default;
const bodies = await json.json()
return {
props: {
bodies
}
}
}
我的 JSON 文件是这样的结构:
{
"stars": [
{
"name": "Sun",
"id": 1,
.....
}
],
"planets": [
{
"name": "Mercury",
"id": 1,
.....
}
],
"moons": [
{
"name": "Moon",
"id": 1,
.....
}
]
}
感谢您的帮助
【问题讨论】:
标签: javascript reactjs next.js