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

React电商项目:如何从Firebase实时数据库动态获取父子节点数据

Solution: Dynamically Fetch and Render All Firebase RTDB Product Categories

To dynamically retrieve and display all parent (e.g., Shirt, Pant) and child (e.g., Formal Shirt) nodes from your Firebase Realtime Database, adjust your data fetching logic to listen to the root products node, then structure the data for nested rendering.

Step 1: Update State and Data Fetching Logic

Replace your existing state and readData function with this structured approach to capture all categories and subcategories:

import { useState, useEffect } from 'react';
import { ref, onValue } from 'firebase/database';
import { database } from './your-firebase-config'; // Adjust to your Firebase config path

function ProductDisplay() {
  // State stores structured category data: [{ name: 'Shirt', subcategories: [{ name: 'Formal Shirt', items: [...] }] }]
  const [productCategories, setProductCategories] = useState([]);

  useEffect(() => {
    // Listen to the entire products node instead of a specific path
    const productsRef = ref(database, '/products');
    
    // Subscribe to real-time updates
    const unsubscribe = onValue(productsRef, (snapshot) => {
      const rawData = snapshot.val();
      if (!rawData) {
        setProductCategories([]);
        return;
      }

      // Transform RTDB's nested object structure into a render-friendly array
      const formattedCategories = Object.entries(rawData).map(([categoryName, subcategoryData]) => {
        const formattedSubcategories = Object.entries(subcategoryData).map(([subcategoryName, itemData]) => ({
          name: subcategoryName,
          items: Object.values(itemData)
        }));

        return {
          name: categoryName,
          subcategories: formattedSubcategories
        };
      });

      setProductCategories(formattedCategories);
    });

    // Clean up subscription on component unmount to prevent memory leaks
    return () => unsubscribe();
  }, []);

  // Render logic below
}

Step 2: Updated Nested Rendering Code

Modify your JSX to map through the structured categories, subcategories, and items dynamically:

<div className="product-container">
  {productCategories.map((category) => (
    <div key={category.name} className="item-category-data-list">
      <h2>{category.name}</h2>
      
      {category.subcategories.map((subcategory) => (
        <div key={subcategory.name} className="item-type">
          <div className="subcategory-header">
            <h3>{subcategory.name}</h3>
            <span className="view-all">view all</span>
          </div>
          
          <div className="item-container-list">
            {subcategory.items.map((item) => (
              <div
                key={item.uuID}
                className="item-data-container"
                onClick={() => updateData(item)}
              >
                <img 
                  className="item-photo" 
                  src={item.image1} 
                  alt={item.productName || 'Product image'} 
                />
                <div className="item-data">
                  <p className="name">{item.productName}</p>
                  <p className="style">{item.type}</p>
                  <div className="item-price-row">
                    <p className="item-discount-price">₹{item.discountPrice}</p>
                    <p className="item-original-price">₹{item.originalPrice}</p>
                    <p className="item-discount">({item.discount})</p>
                  </div>
                  <div className="rating-section">
                    <FontAwesomeIcon className="star-icon" icon={faStar} />
                    <p className="rating">4.7</p>
                    <p className="rating-people">(8.4K)</p>
                  </div>
                  <p className="item-id">ID: {item.uuID}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  ))}
</div>

Key Details

  • Dynamic Path Handling: By listening to the root products node, you automatically capture all new categories/subcategories added to the database without updating code.
  • Data Structuring: Object.entries converts RTDB's key-value pairs into arrays, making it easy to map through nested levels in JSX.
  • Real-Time Cleanup: The useEffect cleanup function stops listening to RTDB updates when the component unmounts, avoiding unnecessary resource usage.

Content of the question comes from Stack Exchange, question author Harshil Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:05:23