简体   繁体   English

如何有条件地计算本机反应中的状态之一?

[英]How do I conditionally count one of the states in react native?

I have JUST started learning React Native with building a quiz app.我刚刚开始通过构建测验应用程序来学习 React Native。

I am counting the following two things;我正在计算以下两件事;

  1. numberOfTry : numbers of tries to answer quizzes. numberOfTry :尝试回答测验的次数。
  2. numberOfCorrectAnswerOnFisrtTry : numbers of try answered on the first try. numberOfCorrectAnswerOnFisrtTry :第一次尝试回答的尝试次数。

No. 1 is ok. 1号没问题。 But No. 2 is killing me for days.但 2 号已经让我死了好几天了。 I would like to know how to change conditionally one of the states when I click a button.我想知道如何在单击按钮时有条件地更改状态之一。

import React, {Component} from 'react';
    import { View, Text, Button } from 'react-native';

    class Quiz extends Component {

        state = {
            quiz_position: 10,
            numberOfTry: 0,
            numberOfCorrectAnserOnFirstTry: 0,
            isFirstTry: true
        }

        updateCount = () => {
            this.setState({
                if (isFirstTry = true) {
                    numberOfCorrectAnserOnFirstTry: numberOfCorrectAnserOnFirstTry +1
                }
                numberOfTry: this.state.numberOfTry+1,
                isFirstTry: false,
              });
        }

        render () {

            return (
                 
                     You tried {this.state.numberOfTry +1 } times.
                     Correct {this.state.numberOfCorrectAnserOnFirstTry} times
                    
                    
                
            )
        }
    }

    export default Quiz

I assume this.state.quiz_position is the index indicating the current question, than you don't need the isFirstTry flag in state.我假设this.state.quiz_position是指示当前问题的索引,而不是状态中不需要isFirstTry标志。

updateCount = () => {
    const { numberOfCorrectAnserOnFirstTry, numberOfTry, quiz_position } = this.state;
    const isFirstTry = quiz_position === 0;

    this.setState({
        numberOfCorrectAnserOnFirstTry: isFirstTry? numberOfCorrectAnserOnFirstTry + 1 : numberOfCorrectAnserOnFirstTry
        numberOfTry: numberOfTry + 1,
   });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM