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

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

  1. Misusing onSnapshot with await: onSnapshot isn't a Promise-based function—it sets up a real-time listener that triggers its callback after your initial set_dataFB(items) runs. That means you're updating state with an empty array before the Firestore data loads.
  2. Incorrectly storing document data: When you push doc objects directly to your array, you're not accessing the actual document fields (like nameENG)—you need to extract doc.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_dataFB inside the onSnapshot callback, we ensure state only updates after Firestore returns the data, triggering a re-render with the correct values.
  • Proper document data handling: Using map to combine doc.id and doc.data() gives you objects that match what your JSX expects (so e.id and e.nameENG are accessible).
  • Cleanup listener: Returning the unsubscribe function from useEffect prevents 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:13:12