简体   繁体   English

取自 Firebase 的对象在通过 forEach 循环推入数组后无法访问

[英]Objects taken from Firebase are inaccessible after being pushed into an array through a forEach loop

I've been trying to create a chat app using react and firebase just for practice since I wanted to try out Firebase, and although I'm able to print out the array of objects that I retrieved into the console, I can't seem to access those objects directly... For example:我一直在尝试使用 react 和 firebase 创建一个聊天应用程序,只是为了练习,因为我想尝试 Firebase,虽然我能够打印出我在控制台中检索到的对象数组,但我似乎无法直接访问这些对象...例如:

if I code " console.log(testArray); " this is what displays in the console, which is all good如果我编写“ console.log(testArray); ”这就是控制台中显示的内容,这一切都很好

0: {name: 'JohnDoe', profile_image: 'imaginary image URL', date: it, message: 'This is my first message to Firebase!'} 0: {name: 'JohnDoe', profile_image: '虚构的图片 URL', date: it, message: '这是我给 Firebase 的第一条消息!'}

but if I try console.log(testArray[0]);但如果我尝试console.log(testArray[0]); it displays undefined in the console它在控制台中显示未定义

Here's my code这是我的代码

import Config from './config';
import { initializeApp } from "firebase/app";
import { 
  getFirestore, 
  addDoc, 
  getDocs, 
  collection, 
  query, 
  orderBy 
} from "firebase/firestore";

function App() {
  
  const firebaseApp = initializeApp(Config);
  const firestore = getFirestore();

  const chat_collection = collection(firestore, "chat");
  const addData = () => {
    addDoc(chat_collection, {
      date: new Date(),
      message: document.getElementById("message").value,
      name: "JohnDoe",
      profile_image: "imaginary image URL"
    });
  }
  
  let testArray = [];
  
  const readData = async () => {
    const chatAppQuery = query(
      collection(firestore, 'chat'),
      orderBy('date')
    ); 

    const chatSnapshot = await getDocs(chatAppQuery);
    
    chatSnapshot.forEach((message) => {
      testArray.push({
        name: message.data().name,
        profile_image: message.data().profile_image,
        date: message.data().date,
        message: message.data().message
      });
    });
  }
  readData();
  console.log(testArray);
  console.log(testArray[0]);

My first time asking for help on here, I'd deeply appreciate it!我第一次在这里寻求帮助,我将不胜感激!

Since readData is an async function, you need to use await (or then() to wait for it results.由于readDataasync function,因此您需要使用await (或then()来等待它的结果。

So:所以:

await readData();
// 👆
console.log(testArray);
console.log(testArray[0]);

If you're in a context where you can't use async / await , you can also use then:如果您处于无法使用async / await的环境中,您也可以使用 then:

readData().then(() => {
         // 👆
  console.log(testArray);
  console.log(testArray[0]);
})

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM