Javascript 我用React做了一个购物车。为什么不是';我的车坏了吗?我所说的工作是指为什么不是';购物车里的数量不是在增加吗?
我用React构建了一个购物车。购物车在1之后未显示购物车中的项目总数。即1是它可以计数的最大计数。我想它计数到1个以上的项目。以下是购物车的Javascript 我用React做了一个购物车。为什么不是';我的车坏了吗?我所说的工作是指为什么不是';购物车里的数量不是在增加吗?,javascript,reactjs,shopping-cart,Javascript,Reactjs,Shopping Cart,我用React构建了一个购物车。购物车在1之后未显示购物车中的项目总数。即1是它可以计数的最大计数。我想它计数到1个以上的项目。以下是购物车的组件: Cart.js import React,{Component}来自“React” 从“../util”导入格式货币; 导出默认类Cart扩展组件{ render(){ const{cartimes}=this.props; //此部分不显示购物车中的商品数量 返回( {cartItems.length==0( 车是空的 ) : ( 您的购物车中有
组件:
Cart.js
import React,{Component}来自“React”
从“../util”导入格式货币;
导出默认类Cart扩展组件{
render(){
const{cartimes}=this.props;
//此部分不显示购物车中的商品数量
返回(
{cartItems.length==0(
车是空的
) : (
您的购物车中有{cartimes.length}
)}
{cartItems.map(项=>(
-
{item.title}
{formatCurrency(item.price)}*{item.count}
this.props.removeFromCart(item)}>Remove
) )}
);
}
}
App.js
我也包括了国家
类应用程序扩展了React.Component{
构造函数(){
超级();
此.state={
产品:数据产品,
项目:[],
大小:“,
排序:“,
};
}
//这部分不起作用
addToCart=(产品)=>{
const cartItems=this.state.cartItems.slice();
让alreadyInCart=false;
cartItems.forEach((项目)=>{
如果(项目编号===产品编号){
item.count++;
alreadyInCart=true;
}
});
如果(!alreadyInCart){
推送({…产品,计数:1});
}
this.setState({cartItems});
};
以下是Github上代码的链接:
`当您尝试将产品添加到购物车时会发生什么情况?使用map而不是forEach,并在增加计数array.slice()和[…array]后返回项目
如果购物车计数中的项目仍然没有超过1,请执行相同的操作。@Augustin检查代码是否在每个部分项中运行。\u id==product.\u id此if块,它肯定已被检查!同时避免``if(!alreadyInCart){carttItems.push({…product,count:1});}```这种情况是因为它不是@Shyam answer中使用的异步函数follow filter。这与原始代码没有什么不同。购物车中的计数没有增加到1以上,因此您也应该在购物车项目中添加对象的形状。从您的问题中不清楚您所说的计数
-您的意思是什么n单个项目s count或cartimes.length`?@Augustin我下载了您的代码并在本地运行,看起来有打字错误:-)。您的项目中没有\u id
属性。它只是id
。如果(item.id==product.id),请将您的代码更改为此if(item.id==product.id){
。它应该可以正常工作:-)另外,在检查代码时,我可以看到三个id为van3
的产品。因此,您需要将一些唯一值传递给id
否则,如果您尝试将所有6个项目添加到购物车中,将只添加4个项目,因为只有4个唯一id。请尝试将所有6个项目添加到购物车中。
addToCart = (product) => {
const cartItems = [...this.state.cartItems];
//follow shyam's answer to check existing item
cartItems.map(eachCartItem=>{
if (eachCartItem._id === product._id) {
eachCartItem.count = eachCartItem.count+1;
}
})
this.setState({cartItems});
};
addToCart = (product) => {
const { cartItems } = this.state;
// find whether the product is there in the cartItems
const isProductPresent = cartItems.some(item => item.id === product.id);
if(isProductPresent){
const updatedCartItems = cartItems.map(item => {
if(item.id === product.id){
return { ...item, count: ++item.count}
}
return item;
})
this.setState({cartItems: updatedCartItems});
}
else {
this.setState({cartItems: [...cartItems, {...product, count: 1}] });
}
};