通过 firebase firestore collectiongroup 映射,不工作
Map through firebase firestore collectiongroup, Not working
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): undefined is not a function (near'...Post.map')
要么
错误(2):theposts.postes 不是函数。 theposts.postes 未定义
从 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>
</>
)
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): undefined is not a function (near'...Post.map') 要么 错误(2):theposts.postes 不是函数。 theposts.postes 未定义
从 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>
</>
)