You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Next.js的page.jsx中用Apollo Client展示GraphQL查询结果

在Next.js page.jsx中用Apollo Client展示GraphQL查询结果

以下是针对你的需求的分步实现方案:

1. 确认Apollo Client基础配置

首先确保项目中已完成Apollo Client的基础配置,比如在lib/apolloClient.js中创建客户端实例:

import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

const httpLink = createHttpLink({
  uri: '你的GraphQL API地址', // 替换为实际接口地址
});

const authLink = setContext((_, { headers }) => {
  // 如需接口认证,在此添加token等逻辑
  return {
    headers: {
      ...headers,
    },
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

export default client;

若使用Next.js App Router,需在根布局或目标页面中用ApolloProvider包裹组件:

import { ApolloProvider } from '@apollo/client';
import client from '@/lib/apolloClient';

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN">
      <body>
        <ApolloProvider client={client}>{children}</ApolloProvider>
      </body>
    </html>
  );
}

2. 在page.jsx中实现查询与渲染

假设使用Next.js App Router(Pages Router逻辑类似,仅路由参数获取方式不同):

'use client'; // 使用React Hooks需添加该指令

import { useQuery, gql } from '@apollo/client';
import { useParams } from 'next/navigation';

// 定义你的GraphQL查询
const GET_CONTENT = gql`
query NewQuery($slug: String!) {
  pageBy(id: "", pageId: 10) {
    id
  }
  postBy(slug: $slug) {
    blocksJSON
    title
    featuredImage {
      node {
        mediaItemUrl
        mediaDetails {
          width
          height
        }
      }
    }
  }
}
`;

export default function ContentPage() {
  const { slug } = useParams(); // 从路由获取slug参数
  const { loading, error, data } = useQuery(GET_CONTENT, {
    variables: { slug }, // 传入查询所需变量
    skip: !slug, // slug不存在时跳过查询
  });

  // 加载状态处理
  if (loading) return <div>加载中...</div>;
  // 错误状态处理
  if (error) return <div>查询出错: {error.message}</div>;

  const { pageBy, postBy } = data;

  return (
    <div className="content-page">
      {/* 渲染pageBy数据 */}
      <section>
        <h2>页面信息</h2>
        <p>页面ID: {pageBy.id}</p>
      </section>

      {/* 渲染postBy数据 */}
      <section>
        <h1>{postBy.title}</h1>
        {postBy.featuredImage?.node && (
          <img
            src={postBy.featuredImage.node.mediaItemUrl}
            alt={postBy.title}
            width={postBy.featuredImage.node.mediaDetails.width}
            height={postBy.featuredImage.node.mediaDetails.height}
          />
        )}
        {/* 解析渲染blocksJSON(注意内容安全) */}
        <div dangerouslySetInnerHTML={{ __html: postBy.blocksJSON }} />
      </section>
    </div>
  );
}

关键注意事项

  • 路由参数获取:Pages Router中使用useRouter()的router.query.slug替代useParams()
  • pageBy中的id为空字符串,大概率无法返回有效数据,建议根据实际需求调整id或pageId参数
  • blocksJSON多为WordPress Gutenberg区块数据,使用dangerouslySetInnerHTML时需确保内容安全,避免XSS风险
  • 如需静态生成(SSG)或服务器端渲染(SSR),可结合Next.js的getStaticProps(Pages Router)或generateStaticParams+服务器端Apollo实例(App Router)实现

内容的提问来源于stack exchange,提问作者AbstractProxy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 14:35:22