Api 更新股票并与React道具交互的按钮
我是React领域的新手,需要一些概念上的帮助。我只希望当按下按钮时,该按钮立即更新API(每次单击都会使库存减少1)。有关可用项目数量的信息来自API。我该怎么做 这是我的购买()方法Api 更新股票并与React道具交互的按钮,api,user-interface,reactjs,Api,User Interface,Reactjs,我是React领域的新手,需要一些概念上的帮助。我只希望当按下按钮时,该按钮立即更新API(每次单击都会使库存减少1)。有关可用项目数量的信息来自API。我该怎么做 这是我的购买()方法 购买(商品){ 这是我的国家({ 总计:this.state.total+parseFloat(项目), 金额:this.state.amount+1 }) } render(){ const allProducts=this.state.products.map((产品,i)=> {返回 }) 返回( 支付
购买(商品){
这是我的国家({
总计:this.state.total+parseFloat(项目),
金额:this.state.amount+1
})
}
render(){
const allProducts=this.state.products.map((产品,i)=>
{返回
})
返回(
支付
支付总额:{this.state.Total}
您已购买{this.state.amount}项
{allProducts}
)
}
}
以及shopItem组件中的buy处理程序
onHandleBuy(event){
event.preventDefault()
this.props.buyMethod(this.props.item.price)
if(this.props.item.stock == 0){
<p className = "shop">No more items available</p>
}else{
this.props.stock - 1
}
}
stockFormat () {
let output
if (this.props.item.stock == 0) {
output = <p className = "shop">No more items available</p>
} else {
output = <p>{this.props.item.stock} items left </p>
}
return output
}
stockFormatButton() {
let button
if (this.props.item.stock == 0) {
button = <p className = "shop">Out of stock</p>
} else {
button = <button onClick = {this.onHandleBuy.bind(this)}>BUY</button>
}
return button
}
render(){
return(
<div className = "product">
<img src = {this.props.item.url} />
{this.stockFormat()}
{this.stockFormatButton()}
</div>
)
}
onHandleBuy(事件){
event.preventDefault()
this.props.buyMethod(this.props.item.price)
if(this.props.item.stock==0){
没有更多可用的商品
}否则{
这个.props.stock-1
}
}
股票格式(){
让输出
if(this.props.item.stock==0){
输出=没有更多可用项目
}否则{
output={this.props.item.stock}剩余的项目
}
返回输出
}
stockFormatButton(){
让按钮
if(this.props.item.stock==0){
按钮=缺货
}否则{
按钮=购买
}
返回按钮
}
render(){
返回(
{this.stockFormat()}
{this.stockFormatButton()}
)
}
希望代码不要太多传递给ShopItem组件的item对象似乎来自父组件状态下的产品数组。这个项目。股票价值是数字的来源,对吗?因此,在递减其值时,需要在父组件的状态下更新该项的值。您正在尝试修改道具本身:
else{this.props.stock-1}
在React中,所有成分的道具都必须是纯的。换句话说,组件不能改变自己的道具
你应该采取与购买方法类似的方法。在父组件的
buy
功能中包含某种减量,然后将更新后的值作为道具传递给ShopItem组件。您应该添加一个代码片段&您的尝试。完成!我只是觉得可能没那么重要
onHandleBuy(event){
event.preventDefault()
this.props.buyMethod(this.props.item.price)
if(this.props.item.stock == 0){
<p className = "shop">No more items available</p>
}else{
this.props.stock - 1
}
}
stockFormat () {
let output
if (this.props.item.stock == 0) {
output = <p className = "shop">No more items available</p>
} else {
output = <p>{this.props.item.stock} items left </p>
}
return output
}
stockFormatButton() {
let button
if (this.props.item.stock == 0) {
button = <p className = "shop">Out of stock</p>
} else {
button = <button onClick = {this.onHandleBuy.bind(this)}>BUY</button>
}
return button
}
render(){
return(
<div className = "product">
<img src = {this.props.item.url} />
{this.stockFormat()}
{this.stockFormatButton()}
</div>
)
}