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

Gatsby中GraphQL查询返回10位数字而非查询数据如何修复

问题原因

你遇到的问题核心来自Gatsby的查询规则限制:

  • 只有通过gatsby-node.js注册的页面/模板组件,才支持定义带变量的页面查询,普通业务组件(比如你写的Products)中导出的graphql查询不会被Gatsby处理成查询结果,只会被编译为查询ID哈希值,也就是你看到的10位数字。
  • 静态查询(useStaticQuery)不支持传入动态变量,所以无法直接在子组件中实现按传入分类动态查询的需求。

解决方法

把产品查询逻辑移到上层的Landing模板组件中,直接用页面上下文传的分类名作为查询变量,拿到结果后再传给Products组件渲染即可,代码修改如下:

1. 修改Landing模板组件

// src/templates/product-pages/landing.js
import React from "react"
import Products from "../../components/Products" // 替换为你实际的Products组件路径
import { graphql } from "gatsby"

const Landing = ({ data, pageContext }) => {
    const categoryName = pageContext.data
    // 取出查询到的分类下产品数据
    const categoryProducts = data.allTaxonomyTermProductCategories.nodes
    return (
        <div>
            <h1>{categoryName}</h1>
            {/* 直接传产品数据给子组件,不需要再传分类名查询 */}
            <Products products={categoryProducts} />
        </div>
    )
}

// 页面查询可以直接调用createPage时传入context的参数作为变量,变量名和context的键对应即可
export const query = graphql`
query($data: String!) {
    allTaxonomyTermProductCategories(filter: {name: {in: $data}}) {
      nodes {
        relationships {
          commerce_product_variation__acyrlic {
            sku
          }
          commerce_product_variation__vinyl {
            sku
          }
        }
      }
    }
  }
`

export default Landing;

2. 简化Products组件

移除Products组件中的查询逻辑,直接接收上层传的产品数据渲染:

const Products = ({products}) => {   
    return (
        <div>
            {/* 按你的需求渲染产品列表即可,示例为输出所有sku */}
            {products.map((categoryNode, index) => (
                <div key={index}>
                    {categoryNode.relationships.commerce_product_variation__acyrlic?.map(product => (
                        <p key={product.sku}>亚克力产品:{product.sku}</p>
                    ))}
                    {categoryNode.relationships.commerce_product_variation__vinyl?.map(product => (
                        <p key={product.sku}>乙烯基产品:{product.sku}</p>
                    ))}
                </div>
            ))}
        </div>
    )
}

export default Products;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:06:00