在React/JS中如何映射带别名的GraphQL查询返回结果
解决方案
你可以根据自己的渲染需求选择以下两种实现方式:
方案1:合并所有赌场数据去重后统一渲染
如果不需要区分分类,只想把所有符合条件的赌场一次性展示,可先合并所有数组并去重:
// 合并四个分类的赌场数据,按slug去重(也可替换为id作为唯一标识) const allCasinos = Object.values(data) .flat() .filter((casino, index, arr) => index === arr.findIndex(item => item.slug === casino.slug) ) // 仅需一次map即可渲染全部 {allCasinos.map(casino => ( <Featured key={casino.slug} casino={casino} /> ))}
方案2:保留分类展示,仅写一次map逻辑
如果需要保留四个分类的独立展示结构,可把分类配置为数组遍历渲染,避免重复写map代码:
// 可自定义分类的展示名称,后续新增分类只需修改这个数组即可 const casinoCategories = [ { key: 'popular_casinos', label: '热门赌场' }, { key: 'awarded_casinos', label: '获奖赌场' }, { key: 'mobile_casinos', label: '移动端适配赌场' }, { key: 'live_casinos', label: '真人娱乐场' } ] // 遍历分类配置,复用渲染逻辑 {casinoCategories.map(({ key, label }) => ( <div className="category-block" key={key}> <h2>{label}</h2> {data[key].map(casino => ( <Featured key={casino.slug} casino={casino} /> ))} </div> ))}
额外优化建议
你的GraphQL查询中四个别名的返回字段完全一致,可以通过片段简化查询代码,避免冗余:
// 定义公共字段片段 const CASINO_FIELDS = gql` fragment CasinoFields on Casino { Mobile Popular Awarded Live slug name logo { url } rating owner founded payout_percentage expert_consensus min_deposit max_deposit payouts total_rating games withdrawals website_experience url aff_link theme_color bonuses_info featured_bonus_1 featured_bonus_type bonuses { name slug title amount code min_deposit value wager cashable bonus_type { name } } deposit_methods { name logo { url } } securities { name logo { url } } supported_devices { name logo { url } } } ` // 简化后的查询语句 const CASINO_QUERY = gql` ${CASINO_FIELDS} query casinos($popular: Boolean, $awarded: Boolean, $mobile: Boolean, $live: Boolean ) { popular_casinos: casinos(where: { Popular: $popular }) { ...CasinoFields } awarded_casinos: casinos(where: { Awarded: $awarded }) { ...CasinoFields } mobile_casinos: casinos(where: { Mobile: $mobile }) { ...CasinoFields } live_casinos: casinos(where: { Live: $live }) { ...CasinoFields } } `
内容的提问来源于stack exchange,提问作者Cult of Tranquility
相关产品推荐
相关产品推荐

