【问题标题】:Counter in the app doesn't function as intended应用程序中的计数器未按预期运行
【发布时间】:2020-12-11 12:06:26
【问题描述】:
 if(this.state.current=== this.state.dataSet.length-1){
    if(this.state.choice.correct===2) { 
      this.setState({IsPassed:true})
    }
    else if(this.state.choice.incorrect===2){ 
      this.setState({IsFailed:true})
  }}else{
    this.setState({current:this.state.current+1})
} 

import React from 'react'

function IsPassed() {
    return (
        <div>
            <h2 className="IsPassed">You are Passed!</h2>
        </div>
    )
}

export default IsPassed;

import React from 'react'

function IsFailed() {
    return (
        <div>
            <h2 className="IsFailed">You are Failed</h2>
        </div>
    )
}

export default IsFailed;

 handleClick(choice){
    if(choice===this.state.dataSet[this.state.current].correct){
      this.setState({correct:this.state.correct+1})
    }
    else{
      this.setState({incorrect:this.state.incorrect+1})
    }
    /*this.setState({isFinished:true})*/
    if(this.state.current=== this.state.dataSet.length-1){
        if(this.state.correct===2) { 
          this.setState({IsPassed:true})
        }
        else if(this.state.incorrect===2){ 
          this.setState({IsFailed:true})
        }
  }
    else{
        this.setState({current:this.state.current+1})
    }    }

total 3 questions but it displaying 4 entries containing correct and incorrect 每当我先选择正确的选项然后再错误,所以当我第三次选择正确的选项时,它最初从 0 开始计数并显示您通过的消息

【问题讨论】:

  • 你能分享你增加/减少正确/错误计数器的代码吗?
  • 能否将代码添加到问题中
  • 好的,我正在这样做
  • this.state 在调用 setState 后不会立即更新,您需要在 fn 中使用局部变量来存储增量值,然后将其设置为 state 并使用局部变量进行比较
  • 完成代码编辑

标签: javascript reactjs function if-statement jsx


【解决方案1】:

您可以在 componentDidUpdate() 函数中调用此函数来查看测试是否完成以及用户是否通过或失败:

if(this.state.current=== this.state.dataSet.length-1){
        if(this.state.correct===2) { 
          this.setState({IsPassed:true})
        }
        else if(this.state.incorrect===2){ 
          this.setState({IsFailed:true})
        }
    }
}

并在句柄中点击:

    if(choice===this.state.dataSet[this.state.current].correct){
          this.setState({
           correct:this.state.correct+1,
           current: this.state.current+1
          })
        }
        else{
          this.setState({
           incorrect:this.state.incorrect+1, 
           current:this.state.current+1
           })
        }

【讨论】:

  • 你可以在componentDidUpdate()函数内部调用这个来查看测试是否完成,用户是否通过:你能详细说明这一点吗??
猜你喜欢
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
相关资源
最近更新 更多