GraphQL查询时如何让返回结果保持过滤数组的原有顺序?
解决方案
问题原因
in 过滤运算符本身不保证返回结果与传入数组的顺序一致,Contentful GraphQL 接口以及 Gatsby 封装的集合查询默认会按内部默认规则(如字母序、创建时间序)返回结果,因此会出现顺序不符的情况。
实现方法
无需修改现有 GraphQL 查询逻辑,在模板组件拿到查询结果后,通过传入的 handles 数组手动重排即可,实现代码如下:
// templates/collection.js 组件内逻辑 const CollectionTemplate = ({ data, pageContext }) => { // 1. 提取查询返回的产品数组 const rawProducts = data.allContentfulProduct.edges.map(edge => edge.node) // 2. 建立 handle 到产品的映射,提升查找效率 const productMap = new Map(rawProducts.map(product => [product.handle, product])) // 3. 按传入的 handles 顺序重排,同时自动过滤下架未查询到的产品 const sortedProducts = pageContext.handles .map(handle => productMap.get(handle)) .filter(Boolean) // 过滤掉已下架不存在的产品 // 后续直接使用 sortedProducts 渲染即可,顺序与传入的 handles 完全一致 // ... }
方案优势
- 改动量极小,无需调整现有查询、gatsby-node 逻辑
- 性能开销可以忽略,即使 handles 数量达到数百级也不会有卡顿
- 自动兼容在售过滤逻辑,已下架未命中查询的产品会被自动排除
内容的提问来源于stack exchange,提问作者hotcakedev
相关产品推荐
相关产品推荐

