我正在使用此代码从 Cloud Firestore 获取数据
const [profile, setProfile] = useState({});
useEffect(() => {
const fetchDoc = async() => {
const response = await db.collection("users").doc(id).get();
const data = response.data();
setProfile({...data});
}
fetchDoc();
}, []);
这会将对象保存到如下所示的状态
{
name: 'sample name',
tertiary: {
name: ['sample 1', 'sample 2', ...]
},
...
}
第一次加载页面时,console.log(profile)
返回一个空对象。但是,据我所知,useEffect 在安装后触发,并获取数据。之后,console.log(profile)
现在返回获取的对象。
现在,由于某种原因,当我通过profile.tertiary.name
时作为组件的 Prop ,我收到一个错误,指出它是 undefined
。每次首次安装页面时都会发生这种情况,并且 useEffect 此后不会执行任何操作。
<CustomBioList education={profile.tertiary.name} />
在 <CustomBioList />
组件,我只是想 console.log(props)
检查是否获取到数据。我是否以错误的方式获取数据?我不明白 useEffect 的完整概念。
最佳答案
profile.tertiary
最初是 undefined
,因此尝试访问profile.tertiary.name
会抛出错误。
您可以通过替换 <CustomBioList education={profile.tertiary.name} />
来添加支票与 (profile.tertiary ? <CustomBioList education={profile.tertiary.name} /> : <span>Loading...</span>
或类似的东西。
关于reactjs - 如何将从 Firestore 获取的数据作为 props 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66097588/