当我使用for或while循环时,我的应用程序崩溃

时间:2019-03-14 13:33:46

标签: javascript reactjs

我开始学习reactjs。我正在做这个非常简单的应用程序。所以我做了一个递减按钮,但是我希望这个按钮仅在项目计数大于或等于零时才起作用。我尝试使用while和for循环,但使用循环时我的应用程序崩溃。有小费吗?谢谢!

这是我的代码:

import React, { Component } from 'react';

class Cart extends Component {
  state = { 
    count: 0,
    message: ""
   };

   handleIncrement = () => {
     this.setState({count: this.state.count + 1});
   }

   handelDecrement = () => {
     while(this.state.count > 0){
       this.setState({count: this.state.count - 1})
     }
   }

   handleStopShopping = () => {
     this.setState({message: this.state.message + "Thank you for your trust! Come back again."})
   }

  render() { 
    return ( 
      <div>
        <h5>Use plus sign to add items to your cart, or use the minus sign to delete items from your cart.</h5>
        {/*Printing the count*/}
        <span className = {this.getBadgeClasses()}>{this.showCount()}</span>
        {/*Increment Button*/}
        <button onClick = {this.handleIncrement} className = {this.incrementButton()}>+</button>
        {/*Decrement Button*/}
        <button onClick = {this.handelDecrement} className = {this.decrementButton()}>-</button> <br></br>

        {/*Info about how much items is in the cart*/}
        <h5><p className = "badge badge-info">{this.itemInfo()}</p></h5>

        <button onClick = {this.handleStopShopping} className = "btn btn-danger btn-sm">Stop Shopping</button> <br></br>
        <h5><p className = "badge badge-dark">{this.state.message}</p></h5>
      </div>
     );
  }

  showCount(){
    let {count} = this.state;
    return count <= 0 ? count = "Zero" : count;
  }

  incrementButton(){
    let btnClasses = "btn m-2 btn-sm btn-";
    btnClasses += this.state.count > 0 && this.state.count < this.state.count ? "dark" : "outline-dark";
    return btnClasses;
  }

  decrementButton(){
    let btnClasses = "btn btn-sm btn-";
    btnClasses += this.state.count === 0 && this.state.count < this.state.count ? "dark" : "outline-dark";
    return btnClasses;
  }

  itemInfo(){
    let itemMessage = "You have " + this.showCount() + " item/s in your cart";
    return itemMessage;
  }

  getBadgeClasses(){
    let badgeClasses = "badge m-2 badge-";
    badgeClasses += this.state.count <= 0 ? "warning" : "primary";
    return badgeClasses;
  }
}

export default Cart

1 个答案:

答案 0 :(得分:3)

让我们说count = 5。

如果您使用

while(this.state.count > 0){
    this.setState({count: this.state.count - 1})
}

它将在完成之前在块中执行代码5次。

您要寻找的是if语句。

if(this.state.count > 0){
    this.setState({count: this.state.count - 1})
}

ALSO 在循环中调用setState会发生异步,因此count可以是1到5之间的任意数字,并且被多次调用,这很可能导致崩溃