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

Apollo查询报错“Expected String, found String”求助

解决GraphQL查询"Expected String, found String"及后续变量错误的问题

我来帮你一步步排查和解决这个问题:

第一个错误的根源:错误的查询参数写法

你最初的查询{ product(_id: String) { brand } }存在语法问题——这里的String是GraphQL的类型标识符,而不是实际的参数值。GraphQL期望你传入一个具体的字符串值或者变量引用,但你直接写了类型名,所以才会报"Expected String, found String"的错误。

正确的带变量查询写法

要使用变量传递_id,你需要按照GraphQL的语法规范来定义变量:

  1. 在查询开头用($变量名: 类型)声明变量
  2. 在字段参数中用$变量名引用这个变量
  3. 确保传入的变量值类型和声明的一致(不需要额外JSON.stringify,如果this.props.id已经是字符串的话直接传即可)

修正后的完整代码

class ProductDetail extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    // 可以先打印确认id的类型,比如console.log(typeof this.props.id)
    return (
      <Query 
        query={GET_PRODUCT} 
        variables={{ id: this.props.id }} // 直接传id,无需JSON.stringify
      >
        {({ loading, error, data }) => {
          if (loading) return <ReactLoading type="spin" className="spinner" color={"black"}></ReactLoading>;
          if (error) return <Alert color="danger">{error.message}</Alert>;
          // 注意:查询的是单个product,直接取data.product而非用map遍历
          const product = data.product;
          return (
            <div>
              {product && <div>品牌:{product.brand}</div>}
            </div>
          );
        }}
      </Query>
    );
  }
}

// 正确定义带变量的GraphQL查询
const GET_PRODUCT = gql`
  query GetProduct($id: String!) { // 声明非空字符串变量$id
    product(_id: $id) { // 引用变量$id作为参数值
      brand
    }
  }
`;

export default ProductDetail;

额外注意点

  • 我把变量名改成了$id(你也可以用$_id保持语义一致),加!表示这是一个非空变量,确保查询时必须传入有效值。
  • 原代码里用data.products.map是错误的,因为你的查询是product(单数),应该直接取data.product。
  • 确认this.props.id的类型:如果它是数字类型,需要转成字符串(比如String(this.props.id))再传入变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:26:06