我在一个网站上工作,学习Reaction和Firebase.我能够从Firebase拉取数据并使用 map 显示在页面上,并 for each 元素返回一个div,但我希望拉出的所有信息都显示在我为它们创建的组件中,以便与页面的其余部分具有一致的样式.
当try 循环访问posts
数组时,我收到错误消息Cannot read properties of undefined (reading 'id')
,但当我console.log
数组时,所有对象都正确显示.有没有按索引访问数组的方法,或者我做错了吗?
以下是MRE:
import React, { useState, useEffect } from 'react'
import { TrendBar, TrendCard } from '../components'
import { db } from '../firebase'
import { collection, getDocs } from 'firebase/firestore'
const Home = () => {
const [posts, setPosts] = useState([]);
const collectionRef = collection(db, 'posts');
useEffect(() => {
const getPosts = async () => {
const data = await getDocs(collectionRef)
setPosts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
}
getPosts()
}, [])
return (
<>
{/* displays all elements of the db on the page */}
{posts.map((post) => {
return <div>
<h1>{post.title}</h1>
</div>
})}
{/* Would like to display the elements like this */}
<TrendBar
firstTrend={
<TrendCard
id={posts[0].id}
image={posts[0].image}
imageAlt={posts[0].imageAlt}
title={posts[0].title}
tags={posts[0].tags}
/>
}
secondTrend={
<TrendCard
id={posts[1].id}
image={posts[1].image}
imageAlt={posts[1].imageAlt}
title={posts[1].title}
tags={posts[1].tags}
/>
}
/>
</>
)
}
谢谢