我在产品页面上有一个Like组件。该组件是一个按钮,当单击该按钮时,该产品将置于类似数组的状态。问题是当我更改产品并单击按钮时,第二个产品未添加到阵列中,而是替换了阵列中的其他产品。例如。我单击衬衫,我看到它已添加到阵列中。我返回并单击另一件衬衫,而不是将两件衬衫都放在阵列中,而是我单击的最后一件衬衫在阵列中。以下是包含“赞”组件和“赞”页面的产品详细信息页面
class Details extends Component {
render() {
const { id } = this.props.match.params;
const productList = this.props.products.map(product => {
if (product.product_id == id) {
return (
<div className="container product_details">
<div className="left">
<div className="images">
<img className="detail_main-photo" src={product.image} />
</div>
</div>
<div className="right">
<h2 className="detail_heading">{product.title}</h2>
<p className="detail_description">{product.description}</p>
<div className="detail_size">
</div>
<p className="detail_price">${product.price}</p>
<Likes product={product} />
</div>
</div>
)
}
})
return (
<div >
{productList}
</div>
)
}
}
export default Details;
class Likes extends Component {
state = {
likes: []
}
addLike = () => {
const button = document.querySelector('.submit')
const Liked = this.state.likes.findIndex(like => {
return like.id === this.props.product.product_id
})
if (Liked) {
const { product } = this.props;
const newLike = {
id: product.product_id,
image: product.image[0],
title: product.title,
price: product.price
}
this.setState({
likes: [...this.state.likes, newLike]
})
}
}
render() {
console.log(this.state)
return (
<button className="submit" onClick={this.addLike}>Add To Wishlist</button>
)
}
}
export default Likes;