我们在 Next JS 上构建了我们的博客,使用 WordPress 作为我们的 API,我们添加了内容直到超过 500 个,但我们的博客不断崩溃,因为我们必须从服务器同时调用所有博客文章。
我们打算创建一个“加载更多”分页按钮功能,单击时一次仅调用特定数量的对象。
这是我们的代码的样子。
//index.tsx
/**
* Caution: Consider this file when using NextJS or GatsbyJS
*
* You may delete this file and its occurrences from the project filesystem if you are using react-scripts
*/
import React from 'react';
import BlogSearch from 'views/BlogSearch';
import Main from 'layouts/Main';
import WithLayout from 'WithLayout';
import Head from 'next/head';
import { getBlogPosts } from '../../lib/api';
const BlogPage = ({ posts }): JSX.Element => {
return (
<>
{' '}
<Head>
<title>Copy and Post - Blog</title>
<meta
property="og:title"
content="Copy and Post - Blog"
key="Copy and Post"
/>
</Head>
<WithLayout
component={() => <BlogSearch posts={posts} />}
layout={Main}
/>
</>
);
};
export default BlogPage;
export async function getStaticProps() {
const posts = await getBlogPosts();
return {
props: {
...posts,
},
};
}
//api.ts
import { homepageQuery, blogPosts, blogPostBySlug } from './queries';
const API_URL = process.env.WP_API_URL;
async function fetchAPI(query, { variables = {} } = {}) {
// Set up some headers to tell the fetch call
// that this is an application/json type
const headers = { 'Content-Type': 'application/json' };
// build out the fetch() call using the API_URL
// environment variable pulled in at the start
// Note the merging of the query and variables
const res = await fetch(API_URL, {
method: 'POST',
headers,
body: JSON.stringify({ query, variables }),
});
// error handling work
const json = await res.json();
if (json.errors) {
console.log(json.errors);
console.log('error details', query, variables);
throw new Error('Failed to fetch API');
}
return json.data;
}
export async function getHomepageSections() {
const data = await fetchAPI(homepageQuery);
return data;
}
export async function getBlogPosts() {
const data = await fetchAPI(blogPosts);
return data;
}
export async function getBlogPostBySlug(slug) {
const data = await fetchAPI(blogPostBySlug, { variables: { id: slug } });
return data;
}
//query.ts
export const homepageQuery = `
query HomepageQuery {
homepageSections {
edges {
node {
homepage {
hero {
animatedwords
heading
subtitle
}
callouts {
title
subtitle
calloutone {
title
subtext
image {
mediaItemUrl
}
}
calloutthree {
title
subtext
image {
mediaItemUrl
}
}
callouttwo {
title
subtext
image {
mediaItemUrl
}
}
}
icongrid {
iconone {
description
icon
title
}
iconfive {
description
icon
title
}
iconfour {
description
icon
title
}
iconsix {
description
icon
title
}
iconthree {
description
icon
title
}
icontwo {
description
icon
title
}
}
}
}
}
}
}
`;
export const blogPosts = `
query BlogPosts {
posts(first: 1000) {
edges {
node {
author {
node {
nickname
}
}
date
slug
featuredImage {
node {
mediaItemUrl
}
}
title
}
}
}
}
`;
export const blogPostBySlug = `
query PostBySlug($id: ID!) {
post(id: $id, idType: SLUG) {
id
content
title
author {
node {
nickname
avatar {
url
}
}
}
date
featuredImage {
node {
mediaItemUrl
}
}
}
}
`;
实现“加载更多”分页并不是一项简单的任务。我将简单介绍如何在客户端和服务器端实现它。
服务器端
您应该有一个采用
limit
和 startAfter
参数的 API 端点。默认情况下,当用户请求没有 startAfter
参数时,返回博客作为限制。
如果
startAfter
参数可用,则将这些 id 在 startAfter
值之后发送博客。
客户端
在客户端,在
getStaticProps
函数中获取一些初始博客,然后每当用户完成滚动或单击“加载更多”按钮时,通过发送 startAfter
参数来获取新博客。如果服务器发回空数组,则停止请求。
对于参考,您可以查看我如何在我的应用程序中实现分页。