我在REACT js 中有购物应用程序。我使用 .map() 函数显示所有产品,并在每个产品前面显示“添加到购物车”按钮。当点击添加到购物车btn 时,它会在本地存储中添加点击的产品 ID,然后我通过从localStorage检索 ID在购物 车中显示这些选定的产品。一切正常。
现在我想要的是在单击一次时禁用“添加到购物车”按钮(仅适用于选定的产品)。我通过设置状态来做到这一点,但它实际上禁用了所有产品前面的所有“添加到购物车”按钮,而不是仅禁用选定的按钮。
我搜索了很多这个问题,我到处都得到的解决方案只是将setState 设置为 true/false 以启用/禁用按钮。我这样做了但没有用,因为它为该页面上的所有产品都这样做。请帮我做什么。
这是我的 REACT JS 代码:
export default class SpareParts extends Component
{
constructor()
{
super()
this.state = {
spareParts: [],
cart: [],
inCart: false,
disabledButton: false
};
this.ViewDeets = this.ViewDeets.bind(this);
this.AddToCart = this.AddToCart.bind(this);
}
ViewDeets= function (part)
{
this.props.history.push({
pathname: '/partdetails',
state: {
key: part
}
});
}
AddToCart(param, e)
{
var alreadyInCart = JSON.parse(localStorage.getItem("cartItem")) || [];
alreadyInCart.push(param);
localStorage.setItem("cartItem", JSON.stringify(alreadyInCart));
this.setState({
inCart: true,
disabledButton: true
})
}
componentDidMount()
{
console.log("Showing All Products to Customer");
axios.get('http://localhost/Auth/api/customers/all_parts.php', {
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}} )
.then(response =>
{
this.setState({
spareParts :response.data.records
});
})
.catch(error => {
if (error) {
console.log("Sorry Cannot Show all products to Customer");
console.log(error);
}
});
}
render()
{
return (
<div id="profileDiv">
{this.state.spareParts.map( part =>
<Col md="3" lg="3" sm="6" xs="6">
<Card>
<Image src={"data:image/png[jpg];base64," + part.Image}
id="partImg" alt="abc" style={ {width: "90%"}} />
<h4> {part.Name} </h4>
<h5> Rs. {part.Price} </h5>
<h5> {part.Make} {part.Model} {part.Year} </h5>
<h5> {part.CompanyName} </h5>
<button
onClick={()=> this.ViewDeets(part) }>
View Details
</button>
<button onClick={() => this.AddToCart(part.SparePartID)}
disabled={this.state.disabledButton ? "true" : ""}>
{!this.state.inCart ? ("Add to Cart") : "Already in Cart"}
</button>
</Card>
</Col>
)}
</div>
);
}
}