添加总价以响应购物车

时间:2020-07-16 13:23:45

标签: reactjs

我是新来的反应者,并按照本教程构建了购物车。该代码非常简单明了,但是我希望它显示产品的总价。我将如何在这段代码中实现它?

这是代码。稍后,我将它们分为3个文件:“产品”,“购物车”和“产品页面”,但在此处全部显示在一起,因此更易于查看。

import React, {useState} from 'react'
import './ProductsPage.css'

const PAGE_PRODUCTS = 'products';
const PAGE_CART = 'cart';

function ProductsPage() {

    const [cart, setCart] = useState ([]);

    const [page, setPage] = useState (PAGE_PRODUCTS);

    const [products] = useState ([
        {
            name: 'Breakfast box ',
            cost:'9.99$',
            image: 'https://images.unsplash.com/photo-1578863950596-a74dfe8267b5?ixlib=rb-1.2.1&auto=format&fit=crop&w=1573&q=80',

        },
        {
            name: 'Breakfast box ',
            cost:'8.99$',
            image: 'https://images.unsplash.com/photo-1557686652-6731ba12410f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80',

        },
    ])

    const addToCart = (product) => {
        setCart ([...cart, {...product}])
    }

    const removeFromCart = (productToRemove) => {
        setCart(cart.filter(product => product !== productToRemove))
    }

    const navigateTo = (nextPage) => {
        setPage(nextPage);
    };

    const renderProducts = () => (
        <>
         <h1>Products</h1>
            <div className="products">
            {products.map((product , index) => (
            <div className="product" key={index}>
               <h3>{product.name}</h3>
               <h4>{product.cost}</h4>
               <img src={product.image} alt={product.name}/>
               <button onClick={() => addToCart(product)}>
                   Add to Cart
                </button>
            </div>
                
                ))}
         </div>
         </>
    );

        const renderCart = () => (
            <>
            <h1>Cart</h1>
               <div className="products">
               {cart.map((product , index) => (
               <div className="product" key={index}>
                  <h3>{product.name}</h3>
                  <h4>{product.cost}</h4>
                  <img src={product.image} alt={product.name}/>
                  <button onClick={() => removeFromCart(product)}>
                      Remove
                   </button>
               </div>
                   
                   ))}
            </div>
            </>
        )

    return (
            <div className="productspage">
            <header>
                <button onClick={()=> navigateTo(PAGE_CART)}>
                    Go to Cart ({cart.length})
                </button>
                <button onClick={()=> navigateTo(PAGE_PRODUCTS)}>
                    View Products
                </button>
            </header>
            {page === PAGE_PRODUCTS && renderProducts()}
            {page === PAGE_CART && renderCart()}
            </div>
    );
};

export default ProductsPage;

3 个答案:

答案 0 :(得分:1)

您可以简单地遍历从对象创建的数组,然后将字符串成本转换为数字(通过在$之前将$替换为空并用+将购物车转换为数字),然后像下面这样对所有参数求和:

Object.keys(cart).reduce(
    (prevVal, currentVal) =>
      prevVal + +cart[currentVal].cost.replace("$", ""),
    0
  )

答案 1 :(得分:0)

在希望显示总费用的地方,在产品列表中调用此功能。

setErrors

这只是一个常规的JavaScript函数,它会迭代产品列表并汇总const getTotalCost = (productList) => { return productList.reduce((totalCost, { cost: itemCost }) => totalCost + parseFloat(itemCost), 0); }; 键,然后将其返回。

它不访问任何道具或状态,因此可以坐在组件的外部。

答案 2 :(得分:0)

检查一下,我添加了带有注释的js代码,以便于理解:

`const [total,setTotal]=useState(0)` //make a new state variable
const cart =[
        {
            name: 'Breakfast box ',
            cost:'9.99$',
            image: 'https://images.unsplash.com/photo-1578863950596-a74dfe8267b5?ixlib=rb-1.2.1&auto=format&fit=crop&w=1573&q=80',

        },
        {
            name: 'Breakfast box ',
            cost:'8.99$',
            image: 'https://images.unsplash.com/photo-1557686652-6731ba12410f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80',

        },
    ]

//modified addToCart
const addToCart = (product) => {
  const products = [...cart, product]
  console.log(products)
 
  const totalPrice = products.reduce((acc, curr)=>{ //calculate total
    let cur =curr.cost.match(/\d./g).join('') //parse string to integer(cost)
      return acc + Number(cur); 
    }, 0)
  console.log("total:", totalPrice);

  // setCart (products);
  //setTotal(totalPrice);
}
//end addToCart


const newProduct = {
            name: 'Breakfast box ',
            cost:'7.99$',
            image: 'https://images.unsplash.com/photo-1557686652-6731ba12410fixlib=rb1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=63',

        }
addToCart(newProduct)