2017-03-21 19 views
0

enter image description here株式を更新し、小道具

私が反応場での初心者です、私はいくつかの概念的な助けを必要とが反応と相互作用ボタン。ボタンを押すたびにそのボタンを即座に更新するようにします(クリックするたびに在庫が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コンポーネントで買いハンドラです

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

完了!私はちょうどそれが関連性がないかもしれないと思った – bwielk

答えて

0

ではありませんホープShopItemコンポーネントに渡されるのは、親コンポーネントの状態で保持されている一連の製品に由来します。このitem.stockの値は、番号がどこから来ているかです。その値を減らすときは、親コンポーネントの状態でそのアイテムの値を更新する必要があります。小道具自体を改造しようとしています: else { this.props.stock - 1 }

すべてのコンポーネントは、その小道具に関して純粋でなければなりません。言い換えれば、コンポーネントはそれ自身の小道具を変更することはできません。

buyMethodの場合と同様の方法を採用してください。親コンポーネントのbuy関数に何らかの減算を含めてから、それらの更新された値を小道具としてShopItemコンポーネントに渡します。

関連する問題