【问题标题】:Redux return total price in cartRedux 返回购物车中的总价
【发布时间】:2018-12-29 19:50:13
【问题描述】:

您好,我的 redux 应用目前正在添加购物车商品,但我想计算总价。

如何在 redux 中做到这一点?

目前我的 Reducer 看起来像这样。

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> 

【问题讨论】:

    标签: redux react-redux


    【解决方案1】:

    您需要为此创建一个选择器,您可以从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)
    

    【讨论】:

    • 你能详细说明一下吗?
    • 这太荒谬了。选择器只是一个函数,它与 react-redux 没有任何关系。 getTotalCost 根据您的示例获取项目列表,这是一个可以调用 reduce 的数组。
    • 详细回答。有关更多信息,您可以通过 google.com/search?q=redux+selectors 找到许多描述选择器用法的帖子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多