Next.js动态生成路由报错:TypeError: users.map is not a function
Next.js getStaticPaths 报错:TypeError: users.map is not a function
在Next.js应用中尝试通过getStaticPaths动态生成用户页面,现有getUsers API可正常返回包含users数组的数据结构,但在getStaticPaths中调用该API并尝试为每个用户名生成路由时,出现TypeError: users.map is not a function错误。
路由生成代码(pages/user/[username].js)
//pages/user/[username].js const Get = async (url) => { return await fetch(url).then(r => r.json()); } export async function getStaticPaths() { const users = Get('/api/getUsers') return { paths: users.map(u => { const username = u.users.username return { params: { username } } }), fallback: false } }
API实现代码(api/getUsers.js)
import clientPromise from "../../lib/mongodb"; import nc from "next-connect"; const app = nc() app.get(async function getUsers(req, res) { const client = await clientPromise; const db = client.db("the-quotes-place"); let users = [] try { const dbUsers = await db .collection("users") .find({}) .toArray(); users = dbUsers return res.json({ users: JSON.parse(JSON.stringify(users)), success: true }) } catch(e) { return res.json({ message: new Error(e).message, success: false, }); } }) export default app
错误原因及修复方案
错误1:未等待异步请求完成
Get是异步函数,调用时未加await,导致users变量实际是一个Promise对象,而非API返回的真实数据。Promise没有map方法,因此触发报错。
错误2:数据结构访问错误
API返回的结构是{ users: [...用户数组], success: boolean },需要先访问response.users拿到数组再遍历;同时每个用户对象的username属性直接挂载在用户对象上,原代码中u.users.username的写法错误。
修复后的getStaticPaths代码
export async function getStaticPaths() { // 加上await等待异步请求完成 const response = await Get('/api/getUsers') // 访问API返回的users数组并遍历 return { paths: response.users.map(u => { const username = u.username return { params: { username } } }), fallback: false } }
内容的提问来源于stack exchange,提问作者Scollier
相关产品推荐
相关产品推荐

