javascript 为什么我的数组没有显示在页面上

omhiaaxx  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(295)

我正在尝试从一个对象数组中呈现列出的属性信息。我在项目的另一部分成功地使用了这个方法,但在这个示例中,我根本没有得到任何东西。
这是我的密码

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([]);
  const array = [];

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

  const getProperties = () => {
    Object.values(users).forEach((user) => {
      Object.values(user?.properties).forEach((property) => {
        array.push(property);
        console.log(property);
      });
    });
    console.log(array);
  };
  useEffect(() => {
    getData();
    getProperties();
  }, [dbRef]);

  return (
    <>
      <div>Properties </div>
      <div>
        {array.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>
    </>
  );
}

什么也没发生,只打印“properties”和“oi”

cidc1ykv

cidc1ykv1#

getData是异步的。当您执行getProperties时,您的users状态仍然是它的初始空数组值。
您似乎没有将users用于任何其他用途,但假设您想保留它,从另一个(users)驱动某个状态(array)的最简单方法是使用memo挂钩。

// this is all better defined outside your component
const usersRef = ref(database, "users");
const getUsers = async () => (await get(usersRef)).val();

export default function Dashboard() {
  const [users, setUsers] = useState({}); // initialise with the correct type

  // Compute all `properties` based on `users`
  const allProperties = useMemo(
    () =>
      Object.values(users).flatMap(({ properties }) =>
        Object.values(properties)
      ),
    [users]
  );

  // Load user data on component mount
  useEffect(() => {
    getUsers().then(setUsers);
  }, []);

  return (
    <>
      <div>Properties </div>
      <div>
        {allProperties.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>
    </>
  );
}

每当users被更改时,memo钩子将重新计算allProperties
如果您不需要users状态,那么就不需要memo钩子了,相反,只需维护您确实需要的状态即可

const [allProperties, setAllProperties] = useState([]); // init with empty array

useEffect(() => {
  getUsers().then((users) => {
    setAllProperties(
      Object.values(users).flatMap(({ properties }) =>
        Object.values(properties)
      )
    );
  });
}, []);

相关问题