无法从Firebase获取posts集合数据,返回undefined求助
解决Firebase集合数据返回undefined的问题
核心问题
你的代码在处理Firebase快照数据时,把文档数据存在了post属性下,但后续渲染和日志打印时直接访问post.content,导致找不到对应字段返回undefined。
修复步骤
1. 修正posts数组结构
修改快照处理逻辑,将文档数据与id直接合并,避免嵌套结构:
原代码:
snapshot.docs.map((doc) => ({ id: doc.id, post: doc.data(), }))
改为:
snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data(), }))
2. 修正数据访问路径
调整日志打印和组件渲染的字段访问方式(结构修正后可直接使用原写法):
// 日志打印 console.log(posts.map((post) => post.content)); // Post组件渲染 <Post user={currentUser?.displayName} content={post.content} caption={post.caption} time={post.timestamp?.toDate().toLocaleString()} />
3. 优化Auth监听逻辑
第一个useEffect缺少依赖数组,会重复注册监听,添加空依赖数组并增加清理函数:
useEffect(() => { const unsubscribe = app.auth().onAuthStateChanged((user) => { setCurrentUser(user) }) return () => unsubscribe() }, [])
4. 处理空值边界情况
使用可选链?.或条件判断,避免currentUser为null时的报错:
{CurrentPage === 'Create' && currentUser && <Create username={currentUser.email}/>}
完整修正代码
import React, { useState, useEffect } from 'react' import "./timeline.css" import {app, db} from "../Authentication/Firebase" import Post from './Posts/Post' import Create from './Create/Create' function Timeline({CurrentPage}) { const [posts, setPosts] = useState([]) const [currentUser, setCurrentUser] = useState(null) const [username, setUsername] = useState("") useEffect(() => { const unsubscribe = app.auth().onAuthStateChanged((user) => { setCurrentUser(user) }) return () => unsubscribe() }, []) useEffect(() => { db.collection("posts") .orderBy("timestamp", "desc") .onSnapshot((snapshot) => { setPosts( snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data(), })) ); }); }, []); console.log(posts.map((post) => post.content)); return ( <div className="timeLine"> <div className='timeLine__left'> <div className='timeline_posts'> {CurrentPage === 'Create' && currentUser && <Create username={currentUser.email}/>} {CurrentPage === 'Post' && posts.map((post) => ( <Post key={post.id} user={currentUser?.displayName} content={post.content} caption={post.caption} time={post.timestamp?.toDate().toLocaleString()} /> ))} </div> </div> </div> ); } export default Timeline
内容的提问来源于stack exchange,提问作者Massimo
相关产品推荐
相关产品推荐

