React从Firestore拉取数据报Cannot read properties of undefined (reading 'profilePic')如何解决
问题根因
你在调用Firestore返回的字段时多写了一层不存在的结构,具体错误逻辑:
- 你在
useEffect的快照回调里,已经通过{...doc.data(), id: doc.id }把单条文档的所有字段直接展开到了posts数组的每一项对象里,也就是说最终生成的post对象本身就包含profilePic、message等所有字段,不存在post.data这个层级。 - 渲染
Post组件时你额外加了.data调用,相当于读取undefined的profilePic属性,自然会抛出对应报错。
另外你定义Feed组件时接收的profilePic、message等props完全没有被使用,属于冗余代码,可以直接删掉。
修复代码
把Post组件传参部分的.data去掉即可:
import React, {useState, useEffect} from 'react'; import Post from './Post'; import db from '../firebase'; // 删掉无用的props const Feed = () => { const [posts, setPosts] = useState([]); //realtime database connection useEffect(() => { db.collection('posts') .orderBy('timestamp','desc') .onSnapshot((snap) => ( setPosts(snap.docs.map((doc) => ({...doc.data(), id: doc.id }))) )); }, []); return ( <div className='feed'> {posts.map((post)=>( <Post key={post.id} profilePic={post.profilePic} message={post.message} timestamp={post.timestamp} username={post.username} image={post.image} /> ))} </div> ); } export default Feed;
可选兜底优化
如果担心个别文档缺字段偶现报错,可以加可选链做兜底处理:
profilePic={post?.profilePic}
也可以直接给Post组件的对应props设置默认值。
内容的提问来源于stack exchange,提问作者Knowexx Ke
相关产品推荐
相关产品推荐

