代码之家  ›  专栏  ›  技术社区  ›  Salman

减少购物车中的退货总价

  •  0
  • Salman  · 技术社区  · 6 年前

    嗨,我的Redux应用程序目前添加购物车项目,但我想功能计算总价格。

    我怎样才能在Redux中做到这一点?

    目前我的 减速器 看起来像这样。

    const cartItems = (state = [], action) => {
        switch (action.type)
        {
            case 'ADD_TO_CART':
            // console.log('CarItems.JS', action.payload)
                if (state.some(cartItem => cartItem.id === action.payload.id)) {
                    // increase qty if item already exists in cart
                    return state.map(cartItem => (cartItem.id === action.payload.id ? { ...cartItem, qty: cartItem.qty + 1 } : cartItem));
                }
                return [...state, { ...action.payload, qty: 1 }]; // else add the new item to cart
    
            case 'REMOVE_FROM_CART':
                return state
                    .map(cartItem => (cartItem.id === action.payload.id ? { ...cartItem, qty: cartItem.qty - 1 } : cartItem))
                    .filter(cartItem => cartItem.qty > 0);
        }
        return state
    } 
    
    export default cartItems 
    

    解决方案

    计算总和并返回。

    const mapStateToProps = (state) => {
        let totalPrice = 0;
        state.map((item) => { 
          totalPrice += item.price * item.qty;
        });
        return {
            cartItems: state,
            totalPrice : totalPrice
        }
    }
    

    在视野中召唤它

    <Text style={styles.total}>Totaal: € {this.props.totalPrice}</Text> 
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   lecstor    6 年前

    您将要为此创建一个选择器,您可以从中使用 mapStateToProps

    function getTotalCost (state) {
      return state.reduce((result, item) => item.qty * item.price + result, 0); 
    }
    

    在组件中..

    import { getTotalCost } from "./items/selectors";
    
    const mapStateToProps = state => {
      return {
        totalCost: getTotalCost(state.items)
      }
    }
    
    class Component extends React.Component {
      render() {
        const { totalCost } = this props;
        ...
      }
    }
    
    export default connect(
      mapStateToProps,
      mapDispatchToProps
    )(Component)
    
    推荐文章