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

React页面数组无法渲染求助:对象数组房产信息不显示

问题分析与解决方案

核心问题

  1. 普通变量无法触发渲染:你用array这个普通变量存储房产数据,React不会追踪普通变量的变化,即使往里面push了数据,组件也不会重新渲染展示内容。
  2. 异步操作时序错误:getData是异步请求Firebase数据的操作,你在useEffect里同步调用getProperties时,users还是初始的空数组,根本遍历不到任何用户的房产数据。
  3. 变量重复初始化:组件每次重新渲染时,array都会被重置为空数组,即使后续有数据也无法保留。

修改后的代码

import { database } from "../../components/firebase";
import { ref, child, get } from "firebase/database";
import { useState, useEffect } from "react";

export default function Dashboard() {
  const dbRef = ref(database);
  const [users, setUsers] = useState([]);
  // 改用React State存储房产列表,让React能追踪变化触发渲染
  const [properties, setProperties] = useState([]);

  const getData = () => {
    get(child(dbRef, "users/"))
      .then((snapshot) => {
        const data = snapshot.val();
        setUsers(data);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  // 当users数据更新后,再处理房产列表
  useEffect(() => {
    if (!users) return;
    
    const propertyArray = [];
    Object.values(users).forEach((user) => {
      // 先判断用户是否有properties,避免报错
      if (user?.properties) {
        Object.values(user.properties).forEach((property) => {
          propertyArray.push(property);
        });
      }
    });
    setProperties(propertyArray);
  }, [users]);

  useEffect(() => {
    getData();
  }, [dbRef]);

  return (
    <>
      <div>Properties </div>
      <div>
        {properties.map((property) => (
          <div key={property.property_id}>
            <h1>{property?.property_name}</h1>
            <p>{property?.description}</p>
            <p>{property?.rooms}</p>
            <p>{property?.phone}</p>
          </div>
        ))}
      </div>
      <p>oi</p>
    </>
  );
}

关键修改说明

  • 替换为State变量:用properties这个React状态替代原array,通过setProperties更新数据,确保React能感知到数据变化并触发组件重新渲染。
  • 调整数据处理时机:新增依赖于users的useEffect,只有当users从Firebase获取完成后,才会遍历用户的房产数据,保证处理时有有效数据。
  • 增加容错判断:遍历用户的properties前先判断是否存在,避免因某个用户没有房产数据导致代码报错。
  • 简化逻辑:移除原getProperties函数,直接在useEffect中处理数据,让逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:02:09