简体   繁体   中英

Calculate SubTotal in React-Redux

I built an eshop and trying to find the right way to display SubTotal on the UI...My code for the "Cart" where I want to place the function calculating SubTotal is the following:

import React, { Component } from "react"
import { Card, CardBody, CardHeader, CardTitle, Row, Col } from "reactstrap"
import PanelHeader from "components/PanelHeader/PanelHeader.js"
import { connect } from "react-redux";
import { removeCart} from "../redux/actions";


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
    const subtotal = (cartProducts.quantity * cartProducts.price).toFixed(2);
    
    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</strong></th>
                      <th scope="col"><strong>Sub 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>{subtotal}</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);

and my redux file where the addToCart and removeFromCart is the following:

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

I know that is better not using redux in order to achieve SubTotal however I posted it for any suggestions! Bare in mind that code:

const subtotal = (cartProducts.quantity * cartProducts.price).toFixed(2);

is not working so I am trying to find another method! Thanks for any help!

I found what's was wrong and I update my question with an answer for future reference:

The syntax was very simple:

<td>{cartProduct.price * cartProduct.quantity}</td>

However, with this code received NaN on my UI. So, I had to change my array of objects. I had a $ sign in front of CartProduct price so returned me every time I clicked addToCart the NaN. By removing from CartProducts the $ sign the code I posted above worked just fine!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM