简体   繁体   English

为什么我的数组没有呈现在我的页面上?

[英]why isn't my array being rendered on my page?

I am trying to render listed property information from an array of objects.我正在尝试从一组对象中呈现列出的属性信息。 I used this method in another part of my project with success, but in this instance, I am not getting anything at all.我在项目的另一部分成功地使用了这种方法,但在这种情况下,我什么也没得到。

here is the code I have这是我的代码

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>
    </>
  );
}

Nothing happens, it only prints "properties" and "oi"没有任何反应,它只打印“properties”和“oi”

getData is asynchronous. getData是异步的。 When you execute getProperties , your users state will still be its initial, empty array value.当您执行getProperties时,您的users state 仍将是其初始的空数组值。

You don't appear to be using users for anything else but assuming you want to keep it, the easiest way to drive some piece of state ( array ) from another ( users ) is to use a memo hook .您似乎没有将users用于其他任何事情,但假设您想保留它,从另一个( users )驱动一些 state( array )的最简单方法是使用备忘录挂钩

// 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>
    </>
  );
}

The memo hook will recompute allProperties any time users is changed.每当users更改时,备忘录挂钩将重新计算allProperties


If you don't need the users state, then there's not much need for the memo hook.如果您不需要users state,那么就不需要备忘录挂钩。 Instead, just maintain the state you do need相反,只需维护您确实需要的 state

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 你能弄清楚为什么我的代码以前可以工作但不能工作吗? - Could you figure out why my code isn't working when it was working previously? 为什么 Cloud Code 不尊重我的 cloudbuild.yaml 文件,但 gcloud beta 构建提交是? - Why isn't Cloud Code honoring my cloudbuild.yaml file but gcloud beta builds submit is? 为什么我的 AWS CloudWatch 警报没有被触发? - Why is my AWS CloudWatch alarm not being triggered? 没有为“对象”类型定义运算符“[]”。 尝试定义运算符'[]'。 为什么我在我的列表视图生成器中收到此错误? - The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'. Why I am getting this error in my listview builder? 为什么我的 AWS SQS 消息即使不符合筛选条件也会被删除? - Why are my AWS SQS messages being deleted even though they don't match the filter criteria? imageFile 没有被识别? - imageFile isn't being recognized? 为什么我的任务的 JSON output 被 AWS Step Functions 转义? - Why is the JSON output of my task being escaped by AWS Step Functions? 为什么我的光束 DoFn 看不到我的全局导入? - Why can't my beam DoFn see my global imports? 为什么它不运行等待 - Why isn't it run await 为什么无法使用苹果按钮登录? - Why isn't sign in with apple button working?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM