【发布时间】:2019-04-17 19:17:12
【问题描述】:
我在 REACT js 中有购物应用程序。我使用 .map() 函数显示所有产品,并在每个产品前面显示“添加到购物车”按钮。当点击添加到购物车 btn 时,它会将点击的产品 ID 添加到本地存储中,然后我通过检索 ID 在 Shopping Cart 中显示这些选定的产品来自 localStorage。这一切都很好。
现在我想要的是在单击一次时禁用“添加到购物车”按钮(仅适用于选定的产品)。我通过设置状态做到了这一点,但它实际上禁用了所有产品前面的所有“添加到购物车”按钮而不是只禁用选定的按钮。
我搜索了很多这个问题,我得到的解决方案只是将 setState 设置为 true/false 以启用/禁用按钮。我这样做了,但没有用,因为它是为那个页面上的 ALL 产品做的。请帮我做什么。
这是我的 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>
);
}
}
【问题讨论】:
标签: javascript reactjs onclick setstate map-function