[英]Flatlist not displaying information retrieved from database
I'm trying to display a list of forums the a user has joined into a flatlist, which is firstly retrieved from firestore via an onSnapshot function in my useLayoutEffect as shown below:我正在尝试显示用户已加入平面列表的论坛列表,该列表首先通过我的 useLayoutEffect 中的 onSnapshot function 从 firestore 检索,如下所示:
useLayoutEffect(() => {
const unsubscribe = onSnapshot(userRef, (snapshot) => {
const joinedForums = [];
if (snapshot.data().myForums.length > 0) {
snapshot.get("myForums").forEach((forumDoc) => {
let docRef = doc(db, "forums", forumDoc);
getDoc(docRef).then((docInf) => {
joinedForums.push({
...docInf.data(),
id: docInf.id,
});
});
});
}
setJoinedForums(joinedForums);
});
return () => unsubscribe();
}, []);
Whenever I load the screen, the flatlist is empty.每当我加载屏幕时,平面列表都是空的。
Here is the code for my flatlist:这是我的平面列表的代码:
<FlatList
data={joinedForums}
renderItem={({ item }) => (
<TouchableOpacity
onPress={() => {
navigation.navigate("ForumDetails", {
forumId: item.id,
});
}}
>
<Card>
<View>
<Text>{item.id}</Text>
<Text>Title: {item.title}</Text>
<Text>Desc: {item.desc}</Text>
<Text>Created By: {item.createdBy}</Text>
</View>
{/* Maybe add a recent message component onSnapshot for each forum */}
<TouchableOpacity
onPress={() => {
leaveForum(item.id);
}}
>
<Text>Leave</Text>
</TouchableOpacity>
</Card>
</TouchableOpacity>
)}
/>
Here is a screenshot of the screen:这是屏幕截图:
After having initially researched on the issue, I discovered that updating a state would cause the flatlist to re-render, so I have tried to manually trigger an update to a separate dummy state through a button which then results for in the flatlist displaying the items correctly.在初步研究了这个问题之后,我发现更新 state 会导致平面列表重新呈现,所以我尝试通过一个按钮手动触发对单独的虚拟 state 的更新,然后在平面列表中显示项目正确。
Here is a screenshot of the screen upon manually updating state:这是手动更新 state 时的屏幕截图:
I'm not sure where to tweak my code to get the flatlist to render the items on first load, without having to manually trigger a state change.我不确定在哪里调整我的代码以使平面列表在第一次加载时呈现项目,而不必手动触发 state 更改。
You should update the state in onSnapshot
after rendering new data retrieved from the snapshot.在渲染从快照中检索到的新数据后,您应该在
onSnapshot
中更新 state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.