如何使用 react.js 计算购物车中产品的总价

时间:2021-06-23 13:58:00

标签: javascript php reactjs laravel

我目前正在做一个使用 react.js 和 Laravel 的项目。我需要获取购物车中产品的总价。通过添加此代码“{item.aprice*item.quantity}”,我已经为每个产品获取了小计(产品价格 * 数量)的输出。现在我需要得到小计的总价。

这是 Cart.js 的代码

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import HeaderTop from './HeaderTop';

function Cart() {
let user = JSON.parse(localStorage.getItem('user-info'))

const [data, setData] = useState([])
useEffect(async () => {
    let result = await fetch("http://localhost:8000/api/getScartList/" + user.cust_id);
    result = await result.json();
    setData(result)

}, [])

async function deleteOperation(id) {
    let result = await fetch("http://localhost:8000/api/scartdelete/" + id, {
        method: 'DELETE'
    });
    result = await result.json();
    console.warn(result)
    getDataa();
}

async function getDataa() {
    let result = await fetch("http://localhost:8000/api/getScartList/" + user.cust_id);
    result = await result.json();
    setData(result)
}

useEffect(() => {
    getDataa();
}, [])


return (
    <div>
        <HeaderTop />
  <section class="cart-section section-b-space">
            <div class="container">
                            <div class="row">
                                <div class="col-sm-12 table-responsive-xs">
                                    <table class="table cart-table">
                                        <thead>
                                            <tr class="table-head">
                                                <th scope="col">image</th>
                                                <th scope="col">product name</th>
                                                <th scope="col">price</th>
                                                <th scope="col">quantity</th>
                                                <th scope="col">action</th>
                                                <th scope="col">total</th>
                                            </tr>
                                        </thead>
                                        {
                                            data.map((item) =>
                                                <tbody>
                                                    <tr>
                                                        <td>
                                                            <Link to={"diamondPot1/" + item.aproduct_id}><img src={"http://localhost:8000/" + item.file_path} /></Link>
                                                        </td>
                                                        <td>{item.name}</td>
                                                        <td>
                                                            <h2>Rs. {item.aprice}/=</h2>
                                                        </td>
                                                        <td>
                                                            <div class="qty-box">
                                                                <div class="input-group">
                                                                    {item.quantity}
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td><a href="#" class="icon"><span onClick={() => deleteOperation(item.aproduct_sc_id)} className="delete "><i class="ti-close"></i></span></a></td>
                                                        <td>
                                                            <h2 class="td-color">Sub total : RS. {item.aprice*item.quantity}/=</h2>                  
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            )}
                                    </table>
                                    <div class="table-responsive-md">
                                        <table class="table cart-table ">
                                            <tfoot>
                                                <tr>
                                                    <td>total price :</td>
                                                    <td>
                                                        <h2> </h2>
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="row cart-buttons">
                                <div class="col-6"><Link to="/" class="btn btn-solid">continue shopping</Link></div>
                                <div class="col-6"><Link to="/checkOut" class="btn btn-solid">check out</Link></div>
                            </div>
            </div>
        </section>
        {/* section end */}

    </div>
  )
}
export default Cart

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

只需使用 array.reduce 函数:

<td>total price :{data.reduce((total, item)=>total+(item.aprice*item.quantity),0)}</td>

答案 1 :(得分:0)

我同意最好的方法是使用 reduce 方法。

这是通过对数组的每个元素应用定义的函数并累积结果来实现的。

假设您的数据结构如下所示:

2021-06-22 21:29:57,096 P3168 [INFO] Config Hook-PreAppDeploy
2021-06-22 21:29:57,205 P3168 [INFO] ============================================================
2021-06-22 21:29:57,205 P3168 [INFO] Command hooks
2021-06-22 21:32:01,483 P3168 [INFO] -----------------------Command Output-----------------------
2021-06-22 21:32:01,483 P3168 [INFO]    log4net:ERROR [RollingFileAppender] Unable to acquire lock on file C:\Program Files\Amazon\ElasticBeanstalk\logs\Hooks.log. The process cannot access the file 'C:\Program Files\Amazon\ElasticBeanstalk\logs\Hooks.log' because it is being used by another process.
2021-06-22 21:32:01,483 P3168 [INFO]    Login failed
2021-06-22 21:32:01,483 P3168 [INFO]    This command [GET /services/messages/restart_required/] needs splunkd to be up, and splunkd is down.
2021-06-22 21:32:01,483 P3168 [INFO] ------------------------------------------------------------
2021-06-22 21:32:01,499 P3168 [ERROR] Exited with error code 160

你可以像下面这样使用reducer:

const data = [
  { 
    name: "item1",
    aprice: 10,
    quantity: 2
  },
  { 
    name: "item2",
    aprice: 10,
    quantity: 2
  },
  { 
    name: "item3",
    aprice: 10,
    quantity: 2
  },
  { 
    name: "item1",
    aprice: 10,
    quantity: 4
  },
]