Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 已删除零部件的状态将覆盖下一个零部件_Javascript_Html_Reactjs_Components_Use State - Fatal编程技术网

Javascript 已删除零部件的状态将覆盖下一个零部件

Javascript 已删除零部件的状态将覆盖下一个零部件,javascript,html,reactjs,components,use-state,Javascript,Html,Reactjs,Components,Use State,我有父组件,名称ShoppingCartDetail。它将呈现多个子组件,名称为ShoppingCartProduct,每个子组件显示产品的数量,它有更改数量的按钮,以及从添加到购物车(如购物网站上的购物车)的产品数组中删除当前产品的按钮 我的问题是:如果改变一个产品的数量,印刷机就会移除。已删除零部件的状态将替代下一零部件的状态。如果我不增加/减少,就不会发生问题 我已经向子组件添加了键属性,但它没有帮助。如果你能给我一些建议,我将不胜感激 1。ShoppingCartDetail.js(父级

我有父组件,名称ShoppingCartDetail。它将呈现多个子组件,名称为ShoppingCartProduct,每个子组件显示产品的数量,它有更改数量的按钮,以及从添加到购物车(如购物网站上的购物车)的产品数组中删除当前产品的按钮

我的问题是:如果改变一个产品的数量,印刷机就会移除。已删除零部件的状态将替代下一零部件的状态。如果我不增加/减少,就不会发生问题

我已经向子组件添加了键属性,但它没有帮助。如果你能给我一些建议,我将不胜感激

1。ShoppingCartDetail.js(父级):

import React from 'react';
import {NavLink} from "react-router-dom";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faReplyAll, faLock} from "@fortawesome/free-solid-svg-icons";
import {connect} from "react-redux";
import ShoppingCartProduct from './ShoppingCartProduct';

const ShoppingCartDetail = (props) => {
    const {Cart, Products, Currency} = props.Data;
    // format thounds seperator
    function formatNumber(num) {
        return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
    }
    /* Remove duplicate product in Cart arr based on ID*/
        const currentCart = [...Cart];
        // get ID list of current Cart
        let currentIdList = [];
        currentCart.forEach((product) => {
            currentIdList.push(product.id);
        })
        // removed duplicated ID
        let removedDuplicateIdList = [];
        currentIdList.forEach((id) => {
            if (!removedDuplicateIdList.includes(id)){
                removedDuplicateIdList.push(id)
            }
        })
        // create product array base on ID list, use this array to render shopping cart
        let splicedProductsList = [];
        removedDuplicateIdList.forEach((id) => {
            Products.forEach((product)=>{
                if (product.id === id){
                    splicedProductsList.push(product)
                }
            })
        })
    /* End remove duplicate product in Cart arr based on ID*/
    // Calculate total amount of Shopping Cart (re-use currentIdList)*/
    var totalAmount = 0;
    currentIdList.forEach((id) => {
        Products.forEach((product)=>{
            if (product.id === id){
                totalAmount += product.price // (default is USD)
            }
        })
    })
    // fortmat money (currency and operator and decimal)
    const showMoneyTotal = (currency, amount) => {
        switch (currency) {
            case "USD":
                return "$ " + formatNumber((amount).toFixed(2))

            case "EUR":
                return "€ " + formatNumber((amount * 0.84).toFixed(2))

            case "GBP":
                return "£ " + formatNumber((amount * 0.76).toFixed(2))

            default:
                return "$ " + formatNumber((amount).toFixed(2))
        }
    }
    
    return (
        <section className="shopping-cart-detail">
            <div className="container">
                <div className="row title">
                    <div className="col">
                        <h4>Your Shopping Cart</h4>
                    </div>
                    <div className="col-auto">
                        <NavLink
                            to = "/all-collection"
                            exact = {true}
                        >
                            <FontAwesomeIcon icon = {faReplyAll} className="icon"/>
                            Continue Shopping
                        </NavLink>
                    </div>
                </div>
                <div className="row shopping-cart-content">
                    <div className="col-6 order">
                        <div className="content">
                            <div className="title">Order Summary</div>
                            <div className="info">
                                <div className="container">
                                    {
                                        splicedProductsList.map((product, index) => {
                                            return (
                                                <ShoppingCartProduct Product = {product} key = {product}></ShoppingCartProduct>
                                            )
                                        })
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="col-3 total-amount">
                        <div className="content">
                            <div className="title">Your Cart Total</div>
                            <div className="info">
                                <div className="money">
                                    <span> {showMoneyTotal(Currency.currency, totalAmount)} </span>
                                </div>
                                <div className="check-out">
                                    <div className="wrap">
                                        <FontAwesomeIcon icon = {faLock} className = "icon"/>
                                        <NavLink
                                            to="/"
                                            exact={true}
                                        >
                                            Proceed To Checkout
                                        </NavLink>
                                    </div>
                                </div>
                                <div className="payment-card">
                                    <img
                                        alt="payment-card"
                                        src={require("../../Assets/images/section-shopping-cart-detail/payment.webp")}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    );
};
const mapStateToProps = (state) => {
    return {
        Data: state
    }
}
export default connect(mapStateToProps)(ShoppingCartDetail)
从“React”导入React;
从“react router dom”导入{NavLink};
从“@fortawesome/react fontawesome”导入{FontAwesomeIcon}”;
从“@fortawesome/free solid svg icons”导入{fareplyal,faLock}”;
从“react redux”导入{connect};
从“./ShoppingCartProduct”导入ShoppingCartProduct;
const ShoppingCartDetail=(道具)=>{
const{Cart,Products,Currency}=props.Data;
//格式thounds分隔符
函数formatNumber(num){
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,$1')
}
/*根据ID删除购物车arr中的重复产品*/
const currentCart=[…Cart];
//获取当前购物车的ID列表
让currentIdList=[];
currentCart.forEach((产品)=>{
currentIdList.push(产品id);
})
//已删除重复的ID
让removedDuplicateIdList=[];
currentIdList.forEach((id)=>{
如果(!removedDuplicateIdList.includes(id)){
removedDuplicateIdList.push(id)
}
})
//基于ID列表创建产品数组,使用此数组呈现购物车
让拼接产品列表=[];
removedDuplicateIdList.forEach((id)=>{
Products.forEach((产品)=>{
if(product.id==id){
拼接产品列表推送(产品)
}
})
})
/*根据ID结束删除购物车arr中的重复产品*/
//计算购物车的总金额(重复使用CurrentIdle)*/
var totalAmount=0;
currentIdList.forEach((id)=>{
Products.forEach((产品)=>{
if(product.id==id){
totalAmount+=product.price//(默认为美元)
}
})
})
//FORMAT货币(货币、运算符和小数)
const showMoneyTotal=(货币、金额)=>{
交换机(货币){
“美元”一案:
返回“$”+格式编号((金额).toFixed(2))
“欧元”案:
返回“€”+格式编号(金额*0.84)。固定(2))
案例“英镑”:
返回“£”+格式编号(金额*0.76)。固定(2))
违约:
返回“$”+格式编号((金额).toFixed(2))
}
}
返回(
你的购物车
继续购物
订单摘要
{
拼接产品列表映射((产品,索引)=>{
返回(
)
})
}
你的购物车总数
{showMoneyTotal(Currency.Currency,totalAmount)}
继续结帐
);
};
常量mapStateToProps=(状态)=>{
返回{
数据:国家
}
}
导出默认连接(MapStateTrops)(ShoppingCartDetail)
2.ShoppingCartProduct.js(儿童)

import React,{useState}来自“React”;
从“react router dom”导入{NavLink};
从“@fortawesome/react fontawesome”导入{FontAwesomeIcon}”;
从“@fortawesome/free solid svg icons”导入{faPen,faTimesCircle}”;
从“react redux”导入{connect};
从“url slug”导入url slug;
const ShoppingCartProduct=(道具)=>{
const{Cart,Currency}=props.Data;
const{Product,dispatch}=props;
//计算购物车中产品的数量
const countProduct=(id)=>{
让计数=0;
Cart.forEach((产品)=>{
if(product.id==id){
计数+=1;
}
})
返回计数;
}
常量[状态,设置状态]=使用状态({
更新数量:countProduct(Product.id),
名称:Product.name
})
//单击加号按钮时增加数量
常量递增加法计数=()=>{
设置状态((prevState)=>{
返回{
import React, {useState} from 'react';
import {NavLink} from "react-router-dom";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faPen, faTimesCircle } from "@fortawesome/free-solid-svg-icons";
import {connect} from "react-redux";
import urlSlug from "url-slug";

const ShoppingCartProduct = (props) => {
    const {Cart, Currency} = props.Data;
    const {Product, dispatch} = props;
    // count quantity of a product in Shopping Cart
    const countProduct = (id) => {
        let count = 0;
        Cart.forEach((product) => {
            if (product.id === id) {
                count += 1;
            }
        })
        return count;
    }
    const [state, setState] = useState({
        update_quantity: countProduct(Product.id),
        name: Product.name
    })
    // increase quantity when click plus button
    const increaseAddedAmount = () => {
        setState((prevState) => {
            return {
                ...prevState,
                update_quantity: prevState.update_quantity + 1
            }
        })
    }
    // decrease quantity when click substract button
    const decreaseAddedAmount = () => {
        if (state.update_quantity > 0) {
            setState((prevState) => {
                return {
                    ...prevState,
                    update_quantity: prevState.update_quantity - 1
                }
            })
        }
    } 
    return (
        <div className={`row product-row ${Product.name}`} key = {Product}>
            <div className="col-2 img">
                <img 
                    alt="product"
                    src = {Product.main__image}
                />
            </div>
            <div className="col-10 product-detail">
                <div className="row name">
                    <div className="col">
                        <NavLink
                            to = {`/product/${urlSlug(Product.name)}`}
                            exact = {true}
                        >
                            {Product.name}
                        </NavLink>
                    </div>
                </div>
                <div className="row price">
                    <div className="col">{showMoney(Currency.currency, 1, Product)}</div>
                </div>
                <div className="row quantity-title">
                    <div className="col">
                        Quantity
                    </div>
                </div>
                <div className="row quantity-row">
                    <div className="col-3 quantity">
                        <div className="wrap">
                            
                            <span 
                                className="decrease"
                                onClick = {()=>{decreaseAddedAmount()}}
                            >-</span>
                            <span className='count'>
                                {state.update_quantity}
                            </span>
                            <span 
                                className="increase"
                                onClick = {()=>{increaseAddedAmount()}}
                            >+</span>
                        </div>
                    </div>
                    <div className="col-3 update-quantity">
                        <div 
                            className="wrap" 
                            onClick = {()=>dispatch({type: "UPDATE", id: Product.id, quantity: state.update_quantity})}
                        >
                            <FontAwesomeIcon icon = {faPen} className="icon"/>
                            Update
                        </div>
                    </div>
                    <div className="col-3 remove-product">
                        <div 
                            className="wrap"
                            onClick = {()=>{dispatch({type: "REMOVE", id: Product.id})}}
                        >
                            <FontAwesomeIcon icon = {faTimesCircle} className="icon"/>
                            Remove
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};
const mapStateToProps = (state) => {
    return {
        Data: state
    }
}
export default connect(mapStateToProps)(ShoppingCartProduct)
const index = this.state.cart.findIndex(
        (cartItem) => cartItem.id === clickedProduct.id
      );
      let newCart = [...this.state.cart];
      if (index >= 0) {
        newCart.splice(index, 1);
      }