ReactJS 结合 Cloud Firestore V9 数据无法渲染至DOM的问题求助
Fix: Firestore Data Not Rendering in React DOM (V9)
Hey Ian, let's break down why your Firestore data shows up in the console but won't render on the page, and fix it step by step!
The Root Issues
- Misusing
onSnapshotwithawait:onSnapshotisn't a Promise-based function—it sets up a real-time listener that triggers its callback after your initialset_dataFB(items)runs. That means you're updating state with an empty array before the Firestore data loads. - Incorrectly storing document data: When you push
docobjects directly to your array, you're not accessing the actual document fields (likenameENG)—you need to extractdoc.data()and pair it with the document ID for your JSX to work.
Corrected Code
Firebase & State Logic
const firebaseApp = initializeApp({ apiKey: "Hidden", authDomain: "Hidden", projectId: "Hidden", }); const db = getFirestore(); const [dataFB, set_dataFB] = useState([]); function getSomethingTEST() { const q = query(collection(db, "WNA-Pasteur-Items")); // Set up real-time listener (no await needed) const unsubscribe = onSnapshot(q, (querySnapshot) => { // Map docs to objects with ID + data const items = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() // Unpack all document fields (including nameENG) })); console.log("Loaded items: ", items.map(item => item.nameENG).join(", ")); // Update state ONLY after data is fetched set_dataFB(items); }); // Return unsubscribe function to clean up on component unmount return unsubscribe; } useEffect(() => { const unsubscribe = getSomethingTEST(); // Clean up listener when component unmounts to prevent memory leaks return () => unsubscribe(); }, []);
JSX (No Changes Needed!)
<p>please work</p> {dataFB.map((e) => ( <div key={e.id}> <h3>{e.nameENG}</h3> </div> ))}
Why This Works
- State updates at the right time: By moving
set_dataFBinside theonSnapshotcallback, we ensure state only updates after Firestore returns the data, triggering a re-render with the correct values. - Proper document data handling: Using
mapto combinedoc.idanddoc.data()gives you objects that match what your JSX expects (soe.idande.nameENGare accessible). - Cleanup listener: Returning the
unsubscribefunction fromuseEffectprevents memory leaks when your component unmounts.
Bonus: This setup also gives you real-time updates—if your Firestore collection changes, the page will automatically refresh with the new data!
内容的提问来源于stack exchange,提问作者Ian
相关产品推荐
相关产品推荐

