NextJS服务端组件返回数据至客户端时出现undefined问题
问题原因及修复方案
你的服务端函数getBenchmarksByUser没有返回数据,导致客户端收到undefined。
具体原因:
- 你在
await getDocs(...)后链式调用了.then(),但then回调里的return res.docs只是回调函数的返回值,并不会成为整个getBenchmarksByUser异步函数的返回值。 - 整个
getBenchmarksByUser函数没有顶层的return语句,所以默认返回undefined。
以下是两种修复方案:
方法一:改用async/await语法(更简洁易读)
去掉.then()和.catch(),用try/catch包裹异步调用,直接返回结果:
'use server' import { db } from "@/lib/firebase"; import { query, getDocs, collection, orderBy, limit } from "firebase/firestore"; export async function getBenchmarksByUser(uid) { console.log("server received uid:", uid); const benchmarksQuery = query( collection(db, 'users/' + uid + '/benchmarks'), orderBy('created'), limit(5) ); try { const res = await getDocs(benchmarksQuery); console.log("server snapshot docs length", res.docs.length); return res.docs; } catch (err) { console.log("ERROR", err); return null; } }
方法二:保留链式调用,确保函数返回Promise结果
如果要继续使用.then()链式写法,需要把整个Promise链作为函数的返回值:
'use server' import { db } from "@/lib/firebase"; import { query, getDocs, collection, orderBy, limit } from "firebase/firestore"; export async function getBenchmarksByUser(uid) { console.log("server received uid:", uid); const benchmarksQuery = query( collection(db, 'users/' + uid + '/benchmarks'), orderBy('created'), limit(5) ); // 返回整个Promise链,让客户端能拿到最终结果 return getDocs(benchmarksQuery).then((res) => { console.log("server snapshot docs length", res.docs.length) return res.docs; }) .catch((err) => { console.log("ERROR",err); return null; }) }
内容的提问来源于stack exchange,提问作者user9154336
相关产品推荐
相关产品推荐

