简体   繁体   English

计算 React-Redux 中的总价

[英]Calculate Total Price in React-Redux

I have a "Cart" component that displays the title, code, quantity, price of products!我有一个“购物车”组件,显示产品的标题、代码、数量、价格! I would like if someone could help calculate "price total" when I send various products into the cart!当我将各种产品放入购物车时,我希望有人可以帮助计算“总价”! My "Cart" component code (bare in mind that {cartProduct.price} is the price of one product but when I add more than one of this product to cart it updates the quantity, but not the Total Price)我的“购物车”组件代码(请记住,{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);

and my reducer file where I update the items quantity (I m not sure if its needed) 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 have an idea that I must create a function that will multiply quantity*price but not sure how to implement it!我有一个想法,我必须创建一个函数来乘以数量 * 价格,但不知道如何实现它! Thank you in advance!先感谢您!

I wouldn't handle this will Redux, It would be better to calculate the values of the cartItems on your React component/page.我不会在 Redux 中处理这个问题,最好计算 React 组件/页面上的cartItems的值。

You can calculate the total price by looping through the cart, getting the price of each product and adding in each price to a single variable.您可以通过遍历购物车、获取每个产品的价格并将每个价格添加到单个变量来计算总价。

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

This way you would not have to update the Redux store every time the user add/removes/updates the quantity of an item.这样您就不必每次用户添加/删除/更新项目的数量时都更新 Redux 存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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