const [theposts, setThePosts] = useState([]);
const myPosts = query(collectionGroup(db, 'posts'));
const unsub = onSnapshot(myPosts, (querySnapshot) => {
querySnapshot.forEach((doc) => setThePosts({
post: doc.data()
}))
return unsub;
})
const Posts = theposts.post;
return (
<>
<StatusBar barStyle = "dark-content" backgroundColor = {'#b300b3'} />
<SafeAreaView style={[styles.container, {marginTop: 5}]}>
<Header navigation = {navigation} />
<Stories />
<ScrollView>
{Posts.map((post, index) => (
<Post post={post} key = {index} />
))}
</ScrollView>
{ /* <BottomTabs icons={bottomTabsIcons} /> */ }
</SafeAreaView>
</>
)
似乎沒有更好的方法來撰寫它,但它仍然會給出錯誤(1):未定義不是函式(near'...Post.map')或錯誤(2):theposts.postes 不是一個函式。theposts.postes 未定義
uj5u.com熱心網友回復:
從 Cloud Firestore獲取posts是一個副作用,應該在useEffect鉤子內完成。
async function getPosts() {
const query = query(collectionGroup(db, "posts"));
const querySnapshot = await getDocs(query);
let posts = [];
querySnapshot.forEach((doc) => {
posts.push(doc.data());
});
setPosts(posts);
}
useEffect(() => {
// Fetch post documents when component mounts
getPosts();
}, []);
然后重構呈現的 JSX 如下
return (
<>
<StatusBar barStyle = "dark-content" backgroundColor = {'#b300b3'} />
<SafeAreaView style={[styles.container, {marginTop: 5}]}>
<Header navigation = {navigation} />
<Stories />
<ScrollView>
{posts.map((post, index) => (
<Post post={post} key = {index} />
))}
</ScrollView>
</SafeAreaView>
</>
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/431316.html
標籤:javascript 火力基地 反应式 谷歌云火库 映射
