Next.js从Firebase Firestore取数时出现map读取undefined的TypeError
问题原因与修复方案
核心错误
你遇到的TypeError: Cannot read property 'map' of undefined和Firestore无关,是数据传递错误导致的:
getStaticProps中通过getDocs获取的data是Firestore的QuerySnapshot对象,它本身不是数组,没有map方法。- 你已经把文档列表处理成了数组格式的
theData,但最后返回props时,错误地把原始的data传给了students,导致组件里的students不是可遍历的数组,调用map就会触发报错。
修复代码
修改getStaticProps的返回逻辑,把处理好的theData传给students,同时移除无用的console.log(data.name):
export const getStaticProps = async () => { const reference = collection(db, "students"); const data = await getDocs(reference); const theData = data.docs.map(doc => ({...doc.data(), id: doc.id})); console.log(theData); // 调试用,查看处理后的学生数据 return { props: {students: theData} // 传递处理完成的数组 } }
额外优化
为了避免Firestore返回空数据时的潜在报错,可以给组件里的map加可选链保护:
{students?.map(student => ( // 你的卡片渲染代码 ))}
内容的提问来源于stack exchange,提问作者Vuyi
相关产品推荐
相关产品推荐

