React Apollo使用GraphQL查询时多布尔筛选条件改为OR逻辑的问题
解决方案
你需要调整GraphQL查询的筛选逻辑,同时在React侧动态构造OR条件数组,具体修改如下:
1. 修改GraphQL查询
首先调整CASINO_QUERY的结构,直接接收完整的where筛选条件作为变量(此处CasinoWhereInput为后端定义的赌场筛选输入类型,如果你使用Hasura可替换为casinos_bool_exp,Prisma可直接使用默认的CasinoWhereInput,具体名称可参考GraphQL接口文档):
import { gql } from "@apollo/client"; const CASINO_QUERY = gql` query casinos($where: CasinoWhereInput!) { casinos(where: $where) { slug name logo { url } rating owner founded payout_percentage expert_consensus } } `; export default CASINO_QUERY;
2. React侧动态生成OR筛选条件
原来直接传递四个布尔参数的方式无法适配灵活的OR逻辑,你需要先根据当前勾选的复选框状态构造筛选条件:
// 新增条件生成方法,放在Query组件渲染前 const getFilterWhere = () => { const orRules = []; // 仅把勾选为true的条件加入OR规则数组 if (this.state.popular) orRules.push({ Popular: true }); if (this.state.awarded) orRules.push({ Awarded: true }); if (this.state.mobile) orRules.push({ Mobile: true }); if (this.state.live) orRules.push({ Live: true }); // 无勾选时返回空对象,即查询所有赌场,若需要无勾选时返回空可替换为{ id: null }这类不存在的条件 if (orRules.length === 0) return {}; return { OR: orRules }; } // 修改Query组件的variables参数 <Query query={CASINO_QUERY} variables={{ where: getFilterWhere() }}> {({ data, loading, error }) => { if (loading) return <p>Loading…</p>; if (error) return <p>Something went wrong</p>; return ( <div> {data.casinos.map((casino) => ( <Featured key={casino.id} casino={casino} /> ))} </div> ); }} </Query>
注意事项
如果你的GraphQL后端规定OR操作符为小写or,只需要把上面返回条件里的OR改为or即可,绝大多数GraphQL服务的过滤规范都兼容上述写法。
内容的提问来源于stack exchange,提问作者Cult of Tranquility
相关产品推荐
相关产品推荐

