问题描述
我一直在寻找使我的网站加载速度更快的方法,在运行速度测试后,我明白我在从 contentful 加载数据的方式上犯了一个错误。我有一个页面,其中列出了所有博客(只有他们的 title
和 image
以及博客列表中可见的一些其他详细信息),而不是仅从内容丰富的 I' m 加载数组 post
的每个数组项(posts
)的所有字段,这自然会占用大量时间并使我的页面变慢。如何仅加载博客列表页面内容中的特定字段,但当我们单击列表中的单个博客时加载所有字段。我正在使用 react static,这是我的配置文件查找帖子部分的方式,其中路径 /blog
是主要博客列表页面,而 /container/Post
是个人博客页面。
let posts = await client
.getEntries({
content_type: "blogPost",order: "-sys.createdAt",include: 1,})
.then((response) => response.items)
.catch(console.error);
console.log("Post -> ",posts.length);
posts = posts.sort((a,b) => {
let keyA = new Date(a.fields.date);
let keyB = new Date(b.fields.date);
// Compare the 2 dates
if (keyA < keyB) return 1;
if (keyA > keyB) return -1;
return 0;
});
在我的退货声明中
{
path: "/blog",getData: () => ({
posts,}),children: posts.map((post) => ({
path: `/${urlBuilder(
post.fields.url ? post.fields.url : post.fields.title
)}`,template: "src/containers/Post",getData: () => ({
post,})),},
这就是我的 posts
从 contentful 返回的样子
解决方法
您可以使用 select
运算符实现此目的。当使用内容丰富的 sdk 时,这会转化为如下内容:
const contentful = require('contentful')
const client = contentful.createClient({
space: '<space_id>',environment: '<environment_id>',accessToken: '<content_delivery_api_key>'
})
client.getEntries({
content_type: '<content_type_id>',select: 'sys.id,fields.<field_name>'
})
.then((response) => console.log(response.items))
.catch(console.error)
特别注意 select: 'sys.id,fields.<field_name>'
部分。您可以在此处仅指定要返回的字段。