[英]How to set state variable by data retrieved from firestore immediately after screen is loaded in react native?
I want to retrieve data from firestore and then set the documentsnapshot data to state variable.我想从 Firestore 中检索数据,然后将文档快照数据设置为 state 变量。 I put the code inside
useEffect()
.我将代码放在
useEffect()
中。 The state variable, document
here, is undefined when the screen is loaded and can only be set after I refresh the app. state 变量,这里的
document
,在屏幕加载时未定义,只能在我刷新应用程序后设置。 How can the variable be set immediately after the screen is loaded?如何在屏幕加载后立即设置变量? Below is the code snippet:
下面是代码片段:
function ToBeReadDetails({route}){
const [document, setDocument] = useState();
const scrollView = useRef();
const bookRef = firestore().collection('BookStore').doc(Type).collection('Books').doc(id);
useEffect(()=>{
bookRef.get().then(doc=>{
setDocument(doc.data());
});
console.log(document);
}, []);
return(
<View>
<ScrollView
ref={scrollView}
showsVerticalScrollIndicator={false}
contentContainerStyle={{alignItems:"center"}}
>
<BookDetails Author={document['Author']}
...
In the first render document will always be undefinded.在第一个渲染文档中将始终未定义。 since getting the data from the firestore will take time.
因为从 Firestore 获取数据需要时间。 it might take 5ms or 500ms depending on various elements, that you cant control, latency... etc.
这可能需要 5 毫秒或 500 毫秒,具体取决于您无法控制的各种元素、延迟……等。
The soultion to your problem is having a fix around that, either you have a loading state that shows up a loader til you get the document, og have condentional rendering that only renders when you get the document您的问题的解决方案是解决这个问题,或者您有一个加载 state,它会显示一个加载器,直到您获得文档,或者只有在您获得文档时才会渲染的条件渲染
like this ex.像这个前。
document['Author'] && (<BookDetails Author={document['Author']})
In your render you have to wait for state to change.在您的渲染中,您必须等待 state 发生变化。 Like this,
像这样,
return !document ?
<View>Loading...</View>
:
<View>
<ScrollView
ref={scrollView}
showsVerticalScrollIndicator={false}
contentContainerStyle={{alignItems:"center"}}
>
<BookDetails Author={document['Author']}
</ScrollView>
</View>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.