изменить инкремент и декремент с помощью двух кнопок React native - PullRequest
0 голосов
/ 10 июля 2020
class Search extends React.Component {

  constructor(props){
    super(props);
    this.state = {count : 0}

    this.M = {Message : " "}
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
    this.result = this.result.bind(this);
    this.result();

  }

  increment(){
    this.setState({count : this.state.count + 1}) ;
    this.result()
    this.forceUpdate();
  }

  decrement() {
    this.setState({count : this.state.count - 1});
    this.result()
    this.forceUpdate();
  }

  result() {
    if (this.state.count >0)
    {
      this.forceUpdate();
      //  this.setState({Message : "positive"});
      this.M.Message = "Positive";
      // this.forceUpdate();
    } else 
    {  
      this.M.Message = "Negative";
      // this.forceUpdate();

      // this.setState({Message : "NEGATIVE "});

    }
    this.forceUpdate();
   
  }



// }
render() {
    return (
      <View>
                <Text style = {{margin: 45, fontSize: 22}}>you have  {this.state.count} Coin</Text>
                <Button 
                      onPress={this.increment}
                      title="win Coin "
                      color="#841584" />
                <Button
                      onPress = {this.decrement}
                      title="lose Coin"
                      color="#841584" />


                      <Text style = {{fontSize : 28}}> Result :  {this.M.Message} </Text>
       </View>
    )  
  }
}

** ошибка заключается в том, что когда счетчик равен 0 или -1, он имеет результат предотвращения, например, когда пользователь нажимает на потерю монеты, результат равен -1, поэтому сообщение "отрицательное", но когда он нажимает в другой раз на кнопке выиграть монету результат будет 0, и результат будет не положительным, а отрицательным, предыдущий результат и только для двух результатов будет 0 и -1 **

1 Ответ

0 голосов
/ 10 июля 2020

Я выяснил источник проблемы. Как вы, возможно, знаете, this.setState () является асинхронным. Вы можете достичь желаемого результата, просто изменив setState на это

increment() {
  this.setState({ count: this.state.count + 1 }, () => {
    this.result();
    this.forceUpdate();
  });
}

Убедитесь, что вы также изменили 'декремент'.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...