[英]I can't print multiple documents from FireStore
I'm able to pull all documents in a collection from Firestore and print each one by one using console.log() command.我可以从 Firestore 中提取集合中的所有文档,并使用 console.log() 命令逐一打印。 But when I want to print these documents to the screen, only the most recent document from the database is printed.
但是当我想将这些文档打印到屏幕上时,只会打印数据库中最新的文档。
here is my code.这是我的代码。
import React, {useState, useEffect, createElement} from 'react'
import styled from 'styled-components'
import { db } from '../firebase';
import { collection, query, where, getDocs } from "firebase/firestore";
function Dashboard () {
let [alims, setAlims] = useState([]);
const getAlim = async() => {
const colRefBuy = collection(db, "alim");
const docsSnap = await getDocs(colRefBuy);
docsSnap.forEach(docBuy => {
let dataRaw = docBuy.data();
let datas = dataRaw.name +' : '+ dataRaw.value +'TL, '+ dataRaw.price+' Adet';
setAlims([...alims, datas]);
})
}
useEffect(() => {
getSatim();
}, []);
return (
<Container>
<BackgroundImage>
<img src='/images/home-background.png' alt='bg'/>
</BackgroundImage>
<Right>
<h2>Alımlar</h2>
<div>
<span>{alims.map((e) =>
<span>{e}</span>
)}</span>
</div>
</Right>
</Container>
)
}
but as I said, it only prints the Tesla document, which is the last among 3 documents.但正如我所说,它只打印特斯拉文档,这是 3 个文档中的最后一个。
You should first map an array containing data from all the documents and update the state only once instead of updating it for every document in the loop.您应该首先 map 一个包含来自所有文档的数据的数组,并仅更新 state 一次,而不是为循环中的每个文档更新它。 Try refactoring the code as shown below:
尝试重构代码,如下所示:
let [alims, setAlims] = useState([]);
const getAlim = async () => {
const colRefBuy = collection(db, "alim");
const docsSnap = await getDocs(colRefBuy);
const data = docsSnap.docs.map((d) => {
return dataRaw.name + ' : ' + dataRaw.value + 'TL, ' + dataRaw.price + ' Adet'
})
setAlims(data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.