首页 > 解决方案 > 在 React-Redux 中计算总价格

问题描述

我有一个“购物车”组件,它显示产品的标题、代码、数量、价格!当我将各种产品放入购物车时,我希望有人可以帮助计算“总价格”!我的“购物车”组件代码(请记住 {cartProduct.price} 是一种产品的价格,但是当我将多个该产品添加到购物车时,它会更新数量,但不会更新总价)

class Cart extends Component {
   removeFromCart = (product) => {
    const cartProducts = this.props.cart 
    const updatedCartProducts = cartProducts.filter(item => item.id !== product.id);
  
  }

  render () {
    const cartProducts = this.props.cart
    return (
      <>
        <PanelHeader size="sm" />
        <div className="content">
          <Row>
            <Col xs={12}>
              <Card>
                <CardHeader>
                  <CardTitle tag="h4">Products List</CardTitle>
                </CardHeader>
                <CardBody>
                <table class="table table-striped table-hover">
                  <thead>
                    <tr>
                      <th scope="col"><strong>#</strong></th>
                      <th scope="col"><strong>Name</strong></th>
                      <th scope="col"><strong>Code Item</strong></th>
                      <th scope="col"><strong>Quantity</strong></th>
                      <th scope="col"><strong>Price Total</strong></th>
                    </tr>
                  </thead>
                    <tbody>
                      {cartProducts.map((cartProduct, index) => (             
                      <tr key={cartProduct.id}>
                    <th scope="row">{index +1}</th>
                    <td>{cartProduct.title}</td>
                    <td>{cartProduct.code}</td>
                    <td>{cartProduct.quantity}</td>
                    <td>{cartProduct.price}</td>
                    <td><button onClick ={() => this.props.removeCart(cartProduct)} className="btn btn-danger cart-button px-4">Remove</button></td>
                      </tr>))}
                    </tbody>
                </table>
              </CardBody>
            </Card>
          </Col>
        </Row>
      </div>
    </>
    )
  }
}


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

const mapDispatchToProps = (dispatch) => { 
      return {
        removeCart: (product) => {dispatch(removeCart(product))}
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart);

和我更新项目数量的reducer文件(我不确定是否需要)如下:

import { ADD_TO_CART } from './constants'
import { REMOVE_FROM_CART } from './constants'
// import { ADD_QUANTITY} from './constants'
// import { SUB_QUANTITY}  from './constants'
// import { EMPTY_CART}  from './constants'


const initialState = {
    cart: [],
  }
const ShoppinReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TO_CART:

      let newCart = [...state.cart]
      let itemIndex = state.cart.findIndex(obj => obj.id === action.payload.id)
      let currItem = state.cart[itemIndex]

      if (currItem) {
      currItem.quantity = parseInt(currItem.quantity) + 1
      state.cart[itemIndex] = currItem
      newCart = [...state.cart]

      }

      else {

      newCart = newCart.concat(action.payload)
      }

      return {
      cart: newCart
      }

    case REMOVE_FROM_CART:
      const cart = [...state.cart]
      const updatedCart = cart.filter(item => item.id !== action.payload.id)

      return {
        ...state,
        cart: updatedCart
      }
    
    default:
    return state
  }
}
  export default ShoppinReducer

我有一个想法,我必须创建一个将数量*价格相乘但不知道如何实现它的函数!先感谢您!

标签: javascriptreactjsredux

解决方案


我不会在 Redux 上处理这个问题,最好计算cartItems你的 React 组件/页面上的值。

您可以通过遍历购物车、获取每个产品的价格并将每个价格添加到单个变量来计算总价格。

{cartItems.reduce((acc, item) => acc + item.quantity * item.price, 0).toFixed(2)}
  • toFixed() 将总价格四舍五入到小数点后 2 位

这样,您就不必在每次用户添加/删除/更新项目的数量时更新 Redux 存储。


推荐阅读