[英]Can't load firestore document data to variable in React-Native
I'm trying to push a new screen to display the selected item's detail, when I get the data it fetches the document correctly, however if I try to set my object to use it in my screen it is undefined, but if I reload the app it does populate the object, here's the code:我正在尝试推送一个新屏幕以显示所选项目的详细信息,当我获取数据时它会正确获取文档,但是如果我尝试将我的 object 设置为在我的屏幕中使用它,它是未定义的,但如果我重新加载它确实填充了 object 的应用程序,代码如下:
const [event, setEvent] = useState();
const getEvent = async (dbx) => {
const eventDoc = doc(dbx, 'events', eventId);
try {
const eventSnapshot = await getDoc(eventDoc);
if(eventSnapshot.exists()) {
const fetchedEvent = eventSnapshot.data();
setEvent(fetchedEvent);
} else {
console.log("Document does not exist")
}
} catch(error) {
console.log(error)
}
return;
}
useEffect(
()=>{
getEvent(db)
console.log("Event Here: ", event);
}
,[])
Setting a variable in the state is an asynchronous operation.在 state 中设置变量是异步操作。 In fact, so is loading data from Firestore, so neither of those operations is done by the time your
console.log("Event Here: ", event)
runs.事实上,从 Firestore 加载数据也是如此,因此在您的
console.log("Event Here: ", event)
运行时,这些操作都不会完成。
If you want to log the event value, use another effect that depends on that state variable to do so:如果要记录事件值,请使用依赖于 state 变量的另一个效果来执行此操作:
useEffect(()=>{
console.log("Event Here: ", event);
},[event])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.