[英]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;我正在计算以下两件事;
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.