我正在使用以下代碼從 firestore 獲取和傳遞資料。我的 Firestore 集合中有四個資料。我能夠獲取所有四個,(我在控制臺上檢查過),但在 NewRecipe組件中,只有第一個資料作為道具傳遞。不知道為什么其他三個資料沒有作為道具傳遞。
這是我獲取資料的組件:
const Home = () => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setIsPending(true);
projectFirestore
.collection("recipes")
.get()
.then((snapshot) => {
if (snapshot.empty) {
setError("No recipes");
setIsPending(false);
} else {
let result = [];
snapshot.docs.forEach((doc) => {
result.push({ id: doc.id, ...doc.data() });
setData(result);
setIsPending(false);
});
}
})
.catch((e) => {
setError(e);
});
}, []);
console.log("data", data);
return (
<div>
{error && <div className="errors">{error}</div>}
{isPending && <div className="Loading">Loading.......</div>}
{data && <NewRecipe data={data} />}
</div>
);
};
export default Home;
這是我接收道具的NewRecipe組件
const NewRecipe = ({data}) => {
console.log("data new recipe", data)
return (
<div className='recipe_list'>
{data.map((item)=>{
return (
<div key={item.id} className='card'>
<h3>{item.title}</h3>
<p>it takes around {item.cookingTime}</p>
<p>{item.method.substring(0,100)}</p>
<Link to={`/recipes/ ${item.id}`}className='btn'> Read more</Link>
</div>
)})}
</div>
)
}
uj5u.com熱心網友回復:
嘗試放置setPending(false)在forEach塊的外面(就在后面)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395792.html
