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

Redux类组件不使用useSelector统计购物车商品数量的实现方法

类组件结合Redux统计购物车总数量的实现方案

类组件不需要改为函数式组件,直接通过connect高阶组件的mapStateToProps即可实现需求,以下是具体修改方案:


方案1:在mapStateToProps中提前计算总数量(推荐)

直接在状态映射时完成总数量计算,逻辑与视图分离,避免组件渲染时重复执行计算逻辑:

const mapStateToProps = state => ({
  cartItems: state.cart.cartItems,
  // 直接计算所有商品的数量总和
  totalQty: state.cart.cartItems.reduce((sum, item) => sum + item.qty, 0)
});

class CartIcon extends React.Component{  
  render(){
    return(
      <View style= {{padding : 5}}>
        <View style={{position :'absolute', height :35, width :30, borderRadius :25 , backgroundColor : '#ffffff' ,right : 10, top:-12 , alignItems:'center', justifyContent:'center',zIndex :2000, }}>
          {/* 直接使用提前计算好的总数量 */}
          <Text style={{color :'blue', fontWeight :'bold' , top :25, right: 15, fontSize:18,borderRadius:30}}> {this.props.totalQty}</Text>
          <Icon name="cart" size ={30} style ={{bottom : 9}} onPress ={()=>this.props.navigation.navigate('Cart')}/>
        </View>
      </View>
    );
  }
}

export default connect(mapStateToProps)(withNavigation(CartIcon));

方案2:修复现有组件内的计算逻辑

如果你希望把计算逻辑放在组件内,只需要修复你现有代码的两个问题即可:

  1. 总数量变量qty用了const声明,无法二次赋值,需要改为let
  2. 原有渲染的是item.length(商品种类数),替换为计算后的总数量qty

修改后的组件代码如下:

const mapStateToProps = state => ({
  cartItems: state.cart.cartItems
});

class CartIcon extends React.Component{  
  render(){
    const items = this.props.cartItems;
    // 改为let声明支持累加
    let qty = 0
    for(let i=0;i<items.length;i++){
      qty += items[i].qty;
    }

    return(
      <View style= {{padding : 5}}>
        <View style={{position :'absolute', height :35, width :30, borderRadius :25 , backgroundColor : '#ffffff' ,right : 10, top:-12 , alignItems:'center', justifyContent:'center',zIndex :2000, }}>
          {/* 替换为计算后的总数量 */}
          <Text style={{color :'blue', fontWeight :'bold' , top :25, right: 15, fontSize:18,borderRadius:30}}> {qty}</Text>
          <Icon name="cart" size ={30} style ={{bottom : 9}} onPress ={()=>this.props.navigation.navigate('Cart')}/>
        </View>
      </View>
    );
  }
}

export default connect(mapStateToProps)(withNavigation(CartIcon));

可选性能优化

如果购物车商品数量较多、计算逻辑复杂,可以引入reselect库创建缓存选择器,只有购物车数据变化时才会重新计算总数量,减少不必要的重复计算开销。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:39:01