错误:getStaticPaths中没有为/location/[id]提供所需的参数(id)作为字符串



我在next.js和mongodb网站工作,我完全遵循本教程,但使用不同的文件/变量名称。当尝试访问动态页面时,我一直遇到这个错误:错误:所需的参数(id)没有作为/location/[id]

的getStaticPaths中的字符串提供。教程:https://www.youtube.com/watch?v=MFuwkrseXVE&ab_channel=Academind刚开始2小时40分钟

PS出于安全原因删除了db info

export async function getStaticPaths(){
const client = await MongoClient.connect(''); ////////// username and password here for mongo db and db name
const db = client.db();

const destinationsCollection = db.collection('destination');
const destinations = await destinationsCollection.find({},{_id: 1}).toArray();
client.close();
return {
fallback: false,
paths: destinations.map((destination) => ({ params: {destinationId: destination._id.toString()},
})),     
};
} 

您的页面是/location/[id],因此您需要在params对象中返回id字段,例如:

{
params: {
id: destination._id.toString()
}
}

你在动态路径中使用的参数很重要

在你的页面位置,例如/location/[anythingInside],你需要确保你的参数内的内容与动态名称文件是相同的,也就是你创建的大括号[]内的内容,例如:

{
params: {
anythingInside: data.id.toString()
}
}

无论你在创建文件时使用的是什么,都必须与参数中的数据相同,例如:path/[anythingInside]params: { anythingInside: { data }}anythingInside必须和params相同

NextJS对其数据获取函数非常细致,您必须非常小心在动态路由页面中使用getStaticPaths()返回参数的方式。我认为这里的问题是,当您返回"params"时,您将数据的id (destination._id.toString())存储到名为"destinationId"的JSON变量中。然而,由于页面名为"[id]", Next将期待一个"id"params"中的JSON变量。所以你的最终代码应该是这样的:

export async function getStaticPaths(){
const client = await MongoClient.connect(''); ////////// username and password here for mongo db and db name
const db = client.db();
const destinationsCollection = db.collection('destination');
const destinations = await destinationsCollection.find({},{_id: 1}).toArray();
client.close();
return {
fallback: false,
paths: destinations.map((destination) => ({ params: {id: destination._id.toString()},
})),     
};

}

希望这能解决问题!

最新更新