React中基于产品ID的列表项上标条件渲染问题求助
问题修复:React中产品上标显示异常
问题根源
你的代码在仅存在ID为20084的产品时,错误地将上标值赋值给了superIndex1,但子组件渲染20084产品时判断的是superIndex2,导致匹配失败,无法显示上标。
修正后的代码
父组件逻辑修改
将componentDidMount中的else if分支调整为给index2赋值1:
componentDidMount() { const { activeUserProducts } = this.props; let index1 = null; let index2 = null; const has198940 = activeUserProducts.products.some(p => p.id === 198940); const has20084 = activeUserProducts.products.some(p => p.id === 20084); if (has198940) { index1 = 1; if (has20084) { index2 = 2; } } else if (has20084) { index2 = 1; // 此处从index1改为index2,匹配子组件的判断逻辑 } this.setState({ superIndex1: index1, superIndex2: index2 }); }
调整后,仅20084存在时superIndex2会被设为1,子组件就能正确渲染它的上标。
可选优化:更直观的逻辑写法
你可以把逻辑拆分成更清晰的形式,避免嵌套判断:
componentDidMount() { const { activeUserProducts } = this.props; const products = activeUserProducts.products; const has198940 = products.some(p => p.id === 198940); const has20084 = products.some(p => p.id === 20084); this.setState({ superIndex1: has198940 ? 1 : null, superIndex2: has20084 ? (has198940 ? 2 : 1) : null }); }
这种写法直接根据两个产品的存在状态计算对应上标值,逻辑更直观,不易出错。
子组件渲染验证
你的子组件渲染逻辑是正确的,只要父组件状态值传递正确,就能正常显示上标:
<h4 className='wallets__table__label wallets__table__label--xxl'> {product.title} {product.id === 198940 && props.superIndex.superIndex1 && <sup>{props.superIndex.superIndex1}</sup>} {product.id === 20084 && props.superIndex.superIndex2 && <sup>{props.superIndex.superIndex2}</sup>} </h4>
内容的提问来源于stack exchange,提问作者danipereiracodes
相关产品推荐
相关产品推荐

