Redux返回购物车中的总价

时间:2018-12-29 19:50:13

标签: redux react-redux

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

如何在Redux中做到这一点?

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
        actions: <Widget>[
          new IconButton(icon: const Icon(Icons.list), onPressed: _loadWeb)
        ],
      ),
      body: new Stack(
        children: <Widget>[
          Container(
            child: new DecoratedBox(
              decoration: new BoxDecoration(
                image: new DecorationImage(
                  image: new AssetImage("images/logo.png"),
                  fit: BoxFit.fill,
                ),
              ),
            ),
          ),
          Center(
            child: _authList(),
          )
        ],
      ),

      floatingActionButton: FloatingActionButton(
        onPressed: getFile,
        tooltip: 'Select file',
        child: Icon(Icons.sd_storage),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    ));
  }
  

解决方案

计算总和并返回。

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
    }
}

1 个答案:

答案 0 :(得分:2)

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