简体   繁体   English

即使数组不为空且 state 不是 null,列表也不会呈现

[英]List not rendering even when the array is not empty and the state is not null

I am trying to retrieve Game names from firestore and display in a list on the page.我正在尝试从 firestore 检索游戏名称并显示在页面的列表中。 For this I am using a component GameList(to display the names retrieved) and Home(to fetch and pass the retrieved data to GameList component).为此,我使用了一个组件 GameList(用于显示检索到的名称)和 Home(用于获取检索到的数据并将其传递给 GameList 组件)。

Here is my code: Home.js:-这是我的代码:Home.js:-

import { useState, useEffect } from 'react';
import { personalDatabaseFirestore } from '../firebase/personalConfig';
import GameList from './GameList';
import './Home.css'

export default function Home(){

const [data, setData] = useState(null);


useEffect(()=>{

    const ref = personalDatabaseFirestore.collection('Games');
    let results = []

    const unsub = ref.onSnapshot((snapshot)=>{
        snapshot.docs.forEach((doc) => {
            results.push({...doc.data(), id: doc.id});
        })
    },(error)=>{
        console.log(error);
    })
    setData(results);
    return ()=>unsub();
},[]);

console.log(data);

return (
    <div className='mainpage-container'>
        {data && <GameList games={data}/>}
    </div>
);

} }

GameList.js:- GameList.js:-

export default function GameList({games}){
  console.log('game list recieved\n', games);
  return (
      <ul>
          {
              games.map((doc)=>{
                  return (<li key={doc.id}>{doc.name}</li>);
              })
          }
      </ul>
  )
}

Console screenshot shows that i am able to retrieve the data successfully from firestore and am able to pass it to GameList component too.控制台屏幕截图显示我能够从 firestore 成功检索数据并且也能够将其传递给 GameList 组件。 But then after logging out the information in gameList component it is not rendering the list that it is supposed to return.但是在注销 gameList 组件中的信息后,它不会呈现它应该返回的列表。

在此处输入图像描述

The onSnapshot() returns data asynchronously so you should use setData within it. onSnapshot()异步返回数据,因此您应该在其中使用setData That'll also ensure any data updates received later are also rendered.这也将确保稍后收到的任何数据更新也被呈现。 Try refactoring the code as shown below:尝试重构代码,如下所示:

useEffect(() => {
  const ref = personalDatabaseFirestore.collection('Games');
  
  const unsub = ref.onSnapshot((snapshot) => {
    const results = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }))
    setData(results);
  })
  return () => unsub();
}, []);

If you need to fetch data only once, then I'd recommend using get() instead of onSnapshot :如果您只需要获取一次数据,那么我建议使用get()而不是onSnapshot

useEffect(() => {
  const ref = personalDatabaseFirestore.collection('Games');

  const fetchData = async () => {
    const snapshot = await ref.get();
    const results = snapshot.docs.map((doc) => ({
      id: doc.id,
      ...doc.data()
    }))
    setData(results);
  }
  
  fetchData();
}, []);

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

相关问题 AWS CLI 在尝试列出 Elastic Beanstalk 应用程序时返回空数组 - AWS CLI returns empty array when attempting to list Elastic Beanstalk applications Firebase promise - 无法设置 state,Z9ED39E2EA931586B6A985A6942EF57E 数组为空 - Firebase promise - unable to set state, state array is empty Bigquery parquet 文件处理列表<string>作为清单<int32>当传递空数组时</int32></string> - Bigquery parquet file treats list<string> as list<int32> when empty array is passed 数组参数,参数为空时为select - Array parameter, select all when the parameter is empty Firebase 数组为空时出现未定义错误 - Firebase undefined error when array is empty 为什么在进行过滤时得到空列表? - Why do I get empty list when doing filter? 使用 FirebaseMessaging.instance.getInitialMessage() 处理终止的 state 时接收 null 值 - Receiving null value when using FirebaseMessaging.instance.getInitialMessage() for handling terminated state 使用 bigquery 计算数组的长度,当空时返回 1 - Count the length of an array with bigquery returns 1 when empty Typescript中解析Uint8Array时Null - Null when parsing Uint8Array in Typescript 为什么我的数组没有更新,即使它在我 console.log() 时更新 - Why isn't my array updating even though it updates when I console.log()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM