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

如何将React-Router的match.params传递给Apollo Client 2.1查询组件?

迁移Apollo旧版本React组件到新查询组件指南

我来帮你把基于Apollo 2.1之前版本的React组件迁移到新的查询写法,顺便理清楚新API的用法~

首先先看你的旧代码(我补全了部分省略的内容):

const Post = ({ data: { loading, error, post } }) => { 
  if (error) return <h1>Error fetching the post!</h1> 
  if (!loading) { 
    return ( 
      <article> 
        <h1>{post.title}</h1> 
        <div className='Post-placeholder'> 
          <img alt={post.title} src={`https://media.graphcms....`} />
        </div>
      </article> 
    )
  }
  return <h1>Loading...</h1>
}

这段代码应该是通过graphql高阶组件(HOC)把data props注入到组件里的,这是Apollo早期的用法。现在Apollo Client 3+更推荐用**useQuery钩子**(函数组件)或者**<Query>组件**来实现查询,下面分别给出迁移方案:

方案1:使用useQuery钩子(推荐)

这是目前函数组件的主流写法,代码更简洁直观:

// 首先导入必要的API
import { useQuery, gql } from '@apollo/client';

// 第一步:显式定义你的查询文档
const GET_POST = gql`
  query GetPost($postId: ID!) {
    post(id: $postId) {
      title
      // 记得加上你需要的图片字段,比如imageUrl
      imageUrl
    }
  }
`;

const Post = ({ postId }) => { 
  // 第二步:用useQuery钩子获取数据,传入查询和变量
  const { loading, error, data } = useQuery(GET_POST, {
    variables: { postId }, // 传递查询所需的变量
  });

  // 第三步:处理加载、错误和数据渲染逻辑
  if (error) return <h1>Error fetching the post!</h1>;
  if (loading) return <h1>Loading...</h1>;

  const { post } = data;
  return ( 
    <article> 
      <h1>{post.title}</h1> 
      <div className='Post-placeholder'> 
        <img alt={post.title} src={post.imageUrl} />
      </div>
    </article> 
  );
};

方案2:使用<Query>组件(组件式写法)

如果你更偏向组件化的写法,或者在类组件中使用,可以用这个方案:

import { Query, gql } from '@apollo/client';

// 同样先定义查询文档
const GET_POST = gql`
  query GetPost($postId: ID!) {
    post(id: $postId) {
      title
      imageUrl
    }
  }
`;

const Post = ({ postId }) => { 
  return (
    <Query query={GET_POST} variables={{ postId }}>
      {/* 渲染props接收查询状态和数据 */}
      {({ loading, error, data }) => {
        if (error) return <h1>Error fetching the post!</h1>;
        if (loading) return <h1>Loading...</h1>;

        const { post } = data;
        return ( 
          <article> 
            <h1>{post.title}</h1> 
            <div className='Post-placeholder'> 
              <img alt={post.title} src={post.imageUrl} />
            </div>
          </article> 
        );
      }}
    </Query>
  );
};

迁移关键点总结

  • 移除对graphql高阶组件的依赖,改用官方推荐的useQuery或<Query>组件
  • 所有查询需要用gql标签显式定义成查询文档,不再隐式通过HOC传递
  • 查询状态(loading/error/data)直接从查询API的返回值获取,不用依赖外部props注入
  • 变量可以直接在查询配置中传递,逻辑更内聚

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:33:27