You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Firebase Firestore获取数据后无法访问属性的问题求助

问题分析与解决

你的核心问题是对polls的结构理解有误:

  • 你通过response.docs.map(...)得到的是一个数组,每个元素是包含data和id的对象;
  • 但你尝试直接用polls.data.id访问,而数组本身没有data属性,自然会触发“无法读取属性”的错误——哪怕数据加载完成后,polls依然是数组,不是单个对象。

修正步骤

1. 正确访问数组内的元素

如果要查看单个元素的属性,需要先指定数组索引,同时要处理数组为空的情况(比如数据还在加载时):

useEffect(() => {
  // 检查数组是否有元素,再访问第一个元素的属性
  if (polls.length > 0) {
    console.log(polls[0].id);
    console.log(polls[0].data.label);
  }
}, [polls])

2. 遍历渲染所有poll数据

如果要在页面展示所有poll内容,在return中使用map遍历数组:

return (
  <div>
    {polls.length === 0 ? (
      <p>加载中...</p>
    ) : (
      polls.map(poll => (
        <div key={poll.id}>
          <h3>ID: {poll.id}</h3>
          <p>标签: {poll.data.label}</p>
          {/* 渲染其他data属性 */}
        </div>
      ))
    )}
  </div>
)

完整修正后的代码

import { useEffect, useState } from "react"
import { collection, getDocs } from "firebase/firestore"
import { db } from '../firebase.config'

function Food() {
  const [polls, setPolls] = useState([])

  useEffect(() => {
    getPolls()
  }, [])

  useEffect(() => {
    if (polls.length > 0) {
      console.log("第一个poll的ID:", polls[0].id);
      console.log("第一个poll的label:", polls[0].data.label);
    }
  }, [polls])

  function getPolls() {
    const pollsRef = collection(db, 'polls');
    
    getDocs(pollsRef).then(response => {
      const pollList = response.docs.map(doc => ({data: doc.data(), id: doc.id}))
      setPolls(pollList)
    }).catch(error => console.log(error.message))
  }
 
  return (
    <div>
      {polls.length === 0 ? (
        <p>加载中...</p>
      ) : (
        polls.map(poll => (
          <div key={poll.id} style={{margin: '1rem 0'}}>
            <h4>Poll ID: {poll.id}</h4>
            <p>Label: {poll.data.label}</p>
          </div>
        ))
      )}
    </div>
  ) 
}

export default Food

关键提醒

  • 始终注意状态的初始值:polls初始是空数组,所以在访问内部元素前必须先判断数组长度,避免在数据加载完成前触发错误;
  • 使用map渲染列表时,必须给每个元素添加唯一的key属性(这里用poll.id是最佳选择)。

内容的提问来源于stack exchange,提问作者m_h9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 02:40:33