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 callsnapshot.data()to get the document's fields directly. - Added existence check:
snapshot.existsensures we don't try to access data from a document that doesn't exist, which prevents unexpected errors. - Adjusted initial state: Initialized
courseNameandcourseDescriptionwith empty strings so your render doesn't throw errors while the data loads (beforecomponentDidMountcompletes). - Simplified state updates: Directly set the state with the fetched
courseDatasince it matches your state structure (assuming the Firestore document hascourseNameandcourseDescriptionfields).
Quick Note on Firestore Snapshots
- Use
collection().get()when you want multiple documents—this returns aQuerySnapshotwith adocsarray you can loop over withforEach. - Use
doc().get()when you want a single document—this returns aDocumentSnapshotwhere you access data directly with.data().
内容的提问来源于stack exchange,提问作者Ryan Nisbet
相关产品推荐
相关产品推荐

