我在 ReactJs 中使用 Contentful 来获取“blogPost”的 content_type,其中有两个帖子。
我可以检索该对象并将其存储到变量中,但是当尝试将其映射到组件时,我没有收到任何回报。
这是我的父组件:
import "./CollectionPosts.css";
import ContentfulClient from "../Contentful/ContentfulClient";
import CollectionPost from "./CollectionPost";
const CollectionPosts = () => {
const posts = [];
ContentfulClient.getEntries({
content_type: "blogPost",
include: 3,
}).then((entry) => {
entry.items.forEach((item) => {
posts.push(item);
});
});
return (
<section id="collection-posts" className="mg-t-lg">
<div className="container">
<h2>
A collection of stuff
<br />
<span>from news to office shenanigans...</span>
</h2>
</div>
<div className="collection-posts">
{posts.map((post) => {
return (
<CollectionPost key={post.sys.id} title={post.fields.blogTitle} />
);
})}
</div>
</section>
);
};
export default CollectionPosts;
这是 CollectionPost.js
function CollectionPost(props) {
return (
<div>
<h3 key={props.key}>{props.title}</h3>
</div>
);
}
export default CollectionPost;
这是我的解决方案,不确定它的效果如何:
import "./CollectionPosts.css";
import ContentfulClient from "../Contentful/ContentfulClient";
import CollectionPost from "./CollectionPost";
import { useState } from "react";
const CollectionPosts = () => {
const [htmlPosts, setHtmlPosts] = useState();
const [isLoading, setIsLoading] = useState(true);
const posts = [];
ContentfulClient.getEntries({
content_type: "blogPost",
include: 3,
}).then((entry) => {
entry.items.forEach((item) => {
posts.push(item);
});
if (isLoading) {
setHtmlPosts(
posts.map((post) => {
return (
<CollectionPost key={post.sys.id} title={post.fields.blogTitle} />
);
})
);
setIsLoading(false);
}
});
return (
<section id="collection-posts" className="mg-t-lg">
<div className="container">
<h2>
A collection of stuff
<br />
<span>from news to office shenanigans...</span>
</h2>
</div>
<div className="collection-posts">{htmlPosts}</div>
</section>
);
};
export default CollectionPosts;