错误:未在 /location/[id] 的 getStaticPaths 中以字符串形式提供必需的参数 (id)

Jac*_*ant 2 mongodb node.js next.js

我正在 next.js 和 mongodb 网站上工作,我完全遵循本教程,但使用不同的文件/变量名称。我在尝试访问动态页面时不断遇到此错误:错误:未在 getStaticPaths 中为 /location/[id] 提供所需参数 (id) 作为字符串

教程:https ://www.youtube.com/watch? v=MFuwkrseXVE&ab_channel=Academind 就在 2 小时 40 分钟之前

PS出于安全原因删除了数据库信息

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()},
    })),     
    };
} 
Run Code Online (Sandbox Code Playgroud)

小智 5

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

{
    params: {
        id: destination._id.toString()
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

{
    params: {
        anythingInside: data.id.toString()
    }
}
Run Code Online (Sandbox Code Playgroud)

创建文件时使用的任何内容都必须与参数中的数据相同,例如: path/[anythingInside]并且params: { anythingInside: { data }} 记住anythingInside必须与里面的数据相同params