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

React读取Firestore单个文档时forEach报错,如何移除forEach?

Solution: Fetching a Single Firestore Document Without forEach

Hey there! No worries at all—we all start somewhere with React and Firestore, so let's fix this up together.

The Root of the Problem

When you use db.collection('courses').doc('testcourse').get(), you're fetching a single document snapshot (a DocumentSnapshot), not a collection of documents (which would be a QuerySnapshot). The DocumentSnapshot doesn't have a docs array, so calling snapshot.docs.forEach() is what's causing your error. You don't need to iterate at all here—you can directly access the document's data!

Fixed Code

Here's how to adjust your component to fetch the single document correctly:

import React, { Component } from 'react';
import '../../CourseStyles/CourseInformation.scss';
import placeholderimg from '../../../Public/Assets/placeholderimage.png';
const firebase = require("firebase");

export default class CourseInformation extends Component {
  // Initialize state with empty values to avoid undefined errors during render
  state = { 
    courseName: '',
    courseDescription: ''
  }

  componentDidMount() {
    const db = firebase.firestore();
    // Fetch the single testcourse document
    db.collection('courses').doc('testcourse').get().then((snapshot)=>{
      if (snapshot.exists) { // Always check if the document exists first!
        const courseData = snapshot.data();
        // Update state with the document's data
        this.setState(courseData);
        console.log('Course data loaded:', this.state);
      } else {
        console.log('No such document!');
      }
    }).catch((error) => {
      console.error('Error getting document:', error);
    });
  }

  render() {
    return (
      <div className = "CourseInformationContainer">
        <div className = "CourseInformationImages">
          <img src = {placeholderimg} className = "CourseInformationImage"/>
          <img src = {placeholderimg} className = "CourseInformationImage"/>
        </div>
        <div className = "CourseInformationTextContainer">
          <div className = "CourseInformationText">
            <h1>{this.state.courseName}</h1>
            <p>{this.state.courseDescription}</p>
            <button> Let's Go</button>
          </div>
        </div>
      </div>
    )
  }
}

Key Changes Explained

  • Removed forEach: Since we're dealing with one document, we don't need to loop—just call snapshot.data() to get the document's fields directly.
  • Added existence check: snapshot.exists ensures we don't try to access data from a document that doesn't exist, which prevents unexpected errors.
  • Adjusted initial state: Initialized courseName and courseDescription with empty strings so your render doesn't throw errors while the data loads (before componentDidMount completes).
  • Simplified state updates: Directly set the state with the fetched courseData since it matches your state structure (assuming the Firestore document has courseName and courseDescription fields).

Quick Note on Firestore Snapshots

  • Use collection().get() when you want multiple documents—this returns a QuerySnapshot with a docs array you can loop over with forEach.
  • Use doc().get() when you want a single document—this returns a DocumentSnapshot where you access data directly with .data().

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 20:27:52