首页 > 解决方案 > 有没有办法计算没有 useselector for redux 的项目数

问题描述

我正在尝试使用 redux 来计算购物车中的商品总数。我知道对于功能组件,我可以使用 useselector 过滤器来做到这一点,但只是想知道我是否可以对类组件做同样的事情。PS我在类组件中屈膝,我真的不想将我的整个结构更改为功能组件来使用钩子,有没有办法做到这一点?

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


class CartIcon extends React.Component{  
        
    render(){   //render the icon button, with style, title and redirect to cart page( to be replaced with shopping cart icon)
       
     
        const item =this.props.cartItems;
        const qty=0
        for(i=0;i<item.length;i++){
         console.log("the item of " + item[i].name + "::" + item[i].qty)
            qty += item[i].qty;
        }
        console.log(qty)
        //console.log(item.length)
    
        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}}> {item.length}</Text>

            <Icon name="cart" size ={30} style ={{bottom : 9}} onPress ={()=>this.props.navigation.navigate('Cart')}
            />

           </View>
       </View>
         
        );
    }
}

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

标签: reactjsreact-nativereduxreact-redux

解决方案


推荐阅读