一个更新库存并与React道具交互的按钮

时间:2017-03-21 19:48:41

标签: api user-interface reactjs

enter image description here

我是React领域的新手,我需要一些概念上的帮助。我只是希望按钮在按下按钮时立即更新API(每次点击都会使股票减少1)。有关可用项目数的信息来自API。我怎样才能做到这一点?

那是我的买()方法

  buy(item){
    this.setState({
      total: this.state.total + parseFloat(item),
      amount: this.state.amount + 1
    })

  }

  render(){
    const allProducts = this.state.products.map((product, i) =>
      {return <ShopItem key = {i} item = {product} buyMethod = {this.buy.bind(this)}/>
    })

    return(
      <div className = "shop">
      <Link to = 'shop/payment'>PAY</Link>
      <p>Total to pay:{this.state.total}</p>
      <p>You have bought {this.state.amount} items</p> 
      {allProducts}
      </div>
      )
  }
}

和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>
      )
  }

希望它没有太多代码

1 个答案:

答案 0 :(得分:0)

看起来传递给ShopItem组件的item对象来自父组件状态下保存的产品数组。这个item.stock值是数字的来源,对吧?因此,当您递减其值时,您需要在父组件的状态中更新该项值。您正在尝试修改道具本身: else { this.props.stock - 1 }

在React中,所有组件必须是纯粹的道具。换句话说,组件不能改变自己的道具。

您应该采用与buyMethod类似的方法。在父组件的buy函数中包含某种递减,然后将这些更新的值作为props传递给ShopItem组件。