我开始为WordPress网站构建一个Next.js前端,使用应用程序路由和GraphQL插件从WordPress获取数据.主页全部设置为显示最新帖子,并且它是一个服务器组件.
import PostCard from "./components/post";
import styles from './page.module.scss'
interface Post {
title: string;
date: string;
excerpt: string;
featuredImage: {
node: {
sourceUrl: string;
};
};
categories: {
edges: {
node: {
name: string;
};
}[];
};
slug: string;
author: {
node: {
name: string;
};
};
}
async function getPosts(cursor: string): Promise<Post[]> {
const endpoint = process.env.WORDPRESS_API_URL || '';
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `
query GetPosts($cursor: String!) {
posts(first: 10, after: $cursor) {
nodes {
title
date
excerpt
featuredImage {
node {
sourceUrl
}
}
categories {
edges {
node {
name
}
}
}
slug
author {
node {
name
}
}
}
}
}
`,
variables: {
cursor: cursor,
},
}),
});
const data = await response.json();
return data.data.posts.nodes;
}
export default async function HomePage() {
const posts = await getPosts("");
return (
<div>
<div className={styles.postsList}>
{posts.map((post) => (
<PostCard post={post} key={post.slug}/>
))}
</div>
<button onClick={ }>Load More</button>
</div>
);
}
挑战是在不使用React的useState
或useEffect
钩子的情况下加载紧跟在该游标之后的下一批帖子(这是我由GraphQL加载的最后一篇帖子的ID),因为这些钩子不会在服务器组件上工作.
如何使"加载更多"按钮与服务器组件一起工作?
我曾try 过使用查询字符串进行分页,但这个计划以失败告终,因为GraphQL的WordPress插件只支持基于指针的分页.