![](/img/trans.png)
[英]React useEffect is returning empty data when page loads for the first time
[英]useEffect with firebase and nextjs undefined when page first loads
我有一个从 firestore 拉入子集合的组件:
import { useEffect, useState } from "react";
import { db } from '../firebase/firebaseInit'
import {useAuth} from '../components/AuthContextProvider'
import { collection, getDocs, setDoc, doc, addDoc } from "firebase/firestore";
type Inputs = {
name: string,
gender: string,
date: any,
}
function Subscriptions({ Component, pageProps }: any) {
const { user } = useAuth()
const [kids, setKids] = useState<any>([])
useEffect(() => {
const getKids = async (user: any) => {
if (user) {
const KidsCollectionRef = collection(doc(collection(db, "users"), user.uid), "kids")
const data = await getDocs(KidsCollectionRef)
setKids(data.docs.map((doc) => ({
...doc.data(), id: doc.id
})))
console.log(kids)
}
}
getKids(user)
}, [])
return (
<>
<h1>Welcome back</h1>
{/* need to loop throug the different prices */}
<div>
{kids.map((kid, index) => (
<span key={index} style={{display: 'block', width: '100%'}}>
{kid.name}
</span>
))}
</div>
</>
)
}
export default Subscriptions
但是,如果我将useEffect
更改为此,它只会 console.logs 来自kids
的数据:
useEffect(() => {
const getKids = async (user: any) => {
if (user) {
const KidsCollectionRef = collection(doc(collection(db, "users"), user.uid), "kids")
const data = await getDocs(KidsCollectionRef)
setKids(data.docs.map((doc) => ({
...doc.data(), id: doc.id
})))
console.log(kids)
}
}
getKids(user)
}, [kids])
这并不理想,因为它会导致无限循环。
这是console.logs:
从firestore获取数据时如何进行useEffect更新?
只需将user.uid
添加到 useEffect dep,uid 不会改变,但它可以是未定义的或值,这意味着它只会在值上触发
useEffect(() => {
const getKids = async () => {
if (user) {
const KidsCollectionRef = collection(doc(collection(db, "users"), user.uid), "kids")
const data = await getDocs(KidsCollectionRef)
setKids(data.docs.map((doc) => ({
...doc.data(), id: doc.id
})))
console.log(kids)
}
}
getKids()
}, [user?.uid])
如果您想查看新的孩子,您可以在 setKids 中更改 state 之前这样做。
useEffect(() => {
//...
setKids(() => {
const newState = data.docs.map((doc) => ({...doc.data(), id: doc.id}))
console.log(newState);
return newState;
})
}, [])
或者只是添加另一个 useEffect
// useEffect with fetch
useEffect(() => { //... }, [])
// useEffect with log
useEffect(() => {
console.log(kids)
}, [kids])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.