![](/img/trans.png)
[英]Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead
[英]Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead? Solve?
這是我的代碼:
import firebase from "../Firebase.js";
import {ThemeProvider} from "@mui/material";
import Post from "../components/posts/Post";
const firestore = firebase.firestore();
function AllPostsPage(props) {
const posts = firestore.collection("posts");
function myFunc() {
posts.get().then((result) => {
result.docs.forEach((post) => {
console.log(post.data().poster);
})
})
}
return (
<ThemeProvider theme={props.theme}>
{posts.get().then((result) => {
result.docs.map((post, index) => {
return <Post theme={props.theme} key={index} title={post.data().title} desc={post.data().desc} poster={post.data().poster} imgUrl={post.data().imgUrl} comments={post.data().comments} />
})
})}
</ThemeProvider>
);
}
export default AllPostsPage;
我嘗試查找其他一些解決方案,但所有人都說您不應該在反應中使用異步代碼。 我沒有在此頁面中定義任何異步代碼,所以我有點卡在這里。
您應該將異步邏輯移出您的 return 語句。 您在此處從 api 獲取數據,並且您在此處使用 then() ,這是異步邏輯。
您可以使用 useState 掛鈎定義 state 並將信息存儲在那里,然后使用 state 呈現您的帖子。 將您的異步邏輯寫入 function 並在 useEffect 中使用空依賴數組調用它,以便在安裝組件時調用它。
首先你導入鈎子:
import React, { useEffect, useState } from "react";
然后在AllPostsPage中定義state:
const [postsData, setPostsData] = useState([]);
然后在 function 中編寫您的異步邏輯並在 useEffect 中調用它:
const getPosts = async () => {
try {
const response = await posts.get();
setPostsData(response.data.data);
} catch(e) { console.log(e);}
}
useEffect(() => {
getPosts();
}, []}
最后使用您的 state 在返回語句中呈現。 ThemeProvider 標簽之間有這樣的事情:
{postsData.docs.map((post, index) => (
<Post theme={props.theme} key={index} title={post.data().title} desc=
{post.data().desc} poster={post.data().poster} imgUrl={post.data().imgUrl}
comments={post.data().comments}
/>
)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.