我是 React 新手,所以我遇到了这个问题,我不明白为什么会发生这种情况,我创建了一个名为 ShoppingCart 的组件,它显示我添加到购物车的所有产品: ShoppingCart.jsx 文件:
import React, { Component } from 'react';
import Product from './Product';
class ShoppingCart extends Component{
state={
products:[
{
id:1,
name:"Burger",
count:2
},
{
id:2,
name:"Cola",
count:3
},
{
id:3,
name:"Fries",
count:4
}
]
}
deleteProduct=(product)=>{
let newProducts = this.state.products.filter((p)=>
{ return p.id !== product.id}
);
this.setState({products:newProducts});
}
reset = ()=>{
let resetProducts = this.state.products.map((p)=>
{ p.count = 0; return p}
);
console.log(resetProducts);
this.setState({products:resetProducts});
}
render(){
return(
<div>
<h1>Products</h1>
<button onClick={this.reset}>reset</button>
{this.state.products.map((product)=>{
return <Product key={product.id} onDelete={this.deleteProduct} product={product}/>
})}
</div>
);
}
}
export default ShoppingCart;
import React, { Component } from 'react';
class Product extends Component {
state = {
id: this.props.product.id,
name: this.props.product.name,
count: this.props.product.count
}
render() {
return (
<div>
<span>{this.state.name}</span>
<span>{this.state.count}</span>
<button onClick = {()=>this.props.onDelete(this.props.product)}>Delete</button>
{/* Ensure onDelete is used correctly */}
</div>
);
}
}
export default Product;
现在我的问题是,当我尝试删除任何产品时,它会被删除,并且新的项目列表会在页面中呈现,但是当我尝试重置元素的计数器时,它会被重置,但新列表不会呈现到页。 那么有人可以帮助我理解它是如何工作的吗?
这是我整理的一些示例代码,我认为它们与您在原始问题中包含的内容一致:
import React, {useState} from 'react';
const initialState = {
products:[
{
id:1,
name:"Burger",
count:2
},
{
id:2,
name:"Cola",
count:3
},
{
id:3,
name:"Fries",
count:4
}
]
};
function Products(){
const [items, setItems] = useState(initialState)
const deleteItem = (itemId) => {
const filteredArray = items.products.filter((x) => x.id !== itemId)
setItems({products: filteredArray})
}
return (
<div>
<p>Product list:</p>
<ul>
{items.products.map((val,idx) => {
return(
<li key={val.id}>
{val.name}
<button onClick={() => deleteItem(val.id)}>Delete</button>
</li>
)
})}
</ul>
</div>);
}
export default Products;
此外,这是类似行为的另一个示例,也许这可以提供一些帮助: