所以我从 firestore 数据库中获取 url,然后将这些 url 用于 img 标签。
但是,我面临的问题是,当页面加载时,数组是空的,但是如果我对代码进行更改(任何更改,甚至是空白空间),数组将在 useeffect 再次触发时填充。希望它能够在第一次获取时获取数据。
控制台日志的第一行是页面加载时,然后第二行是我向 div 添加随机空间时
import React, { useEffect, useState } from "react"
import { proFirestore } from "../firebase/config"
import { collection, onSnapshot, query } from "firebase/firestore"
const Photos = () => {
const [imgs, setImgs] = useState([])
const fetchAllImgs = async () => {
try {
const collectionRef = collection(proFirestore, "images")
const qry = query(collectionRef)
await onSnapshot(qry, (querySnapshot) => {
setImgs(
querySnapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
})
} catch (error) {}
}
useEffect(() => {
fetchAllImgs()
console.log(imgs)
}, [])
return (
<div className="absolute mt-[5%] flex w-full items-center justify-center">
<div className="">
<div>
<button className="h-20 w-20 rounded bg-black text-white"></button>
</div>
<div>
<img className="h-full w-full cursor-pointer" src={imgs[0]}></img>
</div>
</div>
</div>
)
}
export default Photos
我已经尝试了很多东西,例如 .map() ,它有效,但我只想根据其索引从数组中渲染单个项目..
任何帮助都会很棒吗?
如果改成这样,可以吗?
const fetchAllImgs = async () => {
try {
const collectionRef = collection(proFirestore, "images");
const qry = query(collectionRef);
const querySnapshot = await getDocs(qry);
const imgData = querySnapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}));
setImgs(imgData);
} catch (error) {
console.error("Error fetching images:", error);
}
};
或者这个:
const fetchAllImgs = () => {
const collectionRef = collection(proFirestore, "images");
const qry = query(collectionRef);
getDocs(qry)
.then((querySnapshot) => {
const imgData = querySnapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}));
setImgs(imgData);
})
.catch((error) => {
console.error("Error fetching images:", error);
});
};