我正在開發一個網站并學習 React 和 Firebase。我能夠從 Firebase 中提取資料并使用地圖將其顯示在頁面上,并為每個元素回傳一個 div,但是我希望提取的所有資訊都顯示在我為它們創建的組件中,以便與其余部分具有一致的樣式這頁紙。
嘗試回圈遍歷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}
/>
}
/>
</>
)
}
謝謝
uj5u.com熱心網友回復:
您需要在繪制之前檢查 array.length !== 0 。有幾種方法可以檢查它,最簡單的一種是:
posts.length && posts.map((post) => {
return <div>
<h1>{post.title}</h1>
</div>
})}
posts?.map((post) => {
return <div>
<h1>{post.title}</h1>
</div>
})}
此外,為了防止將來出現錯誤,我們有新的語法:
<TrendBar
firstTrend={
<TrendCard
**id={posts?.[0].id}**
image={posts[0].image}
imageAlt={posts[0].imageAlt}
title={posts[0].title}
tags={posts[0].tags}
/>
可選呼叫,可以通過func?.()的方式呼叫事件函式。
您需要進行這些檢查,因為資料是異步傳入的,因此在陣列下載之前您無法獲取 array[n] elem。
如果您有更多問題,請不要猶豫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/505212.html
標籤:Google Cloud Collective javascript 反应 火力基地
