繁体   English   中英

使用Break循环无限循环 ReactJs

[英]Loop for with loop infinite using Break? ReactJs

发生了什么:我有两个变量: ScorePlayerScoreDealer ,它们是每个cardsPlayercardsDealer主数组中包含的元素cardsPlayer和的cardsDealer

我想要做的是验证。 如果ScoreDealer变量的值小于ScorePlayer变量的值,我希望它在其中添加更多元素( ScoreDealer ),但我不希望元素的总和超过21的值。

我使用了Break方法,但无限循环继续并挂起了应用程序。

执行此功能:

finishGame = () => {
  const scorePlayer = this.state.cardsPlayer.reduce((a, b) => a + b);

  const scoreDealer = this.state.cardsDealer.reduce((a, b) => a + b);

  for (let i = scoreDealer; scoreDealer < scorePlayer; i++) {

    this.setState({
      cardsDealer: this.state.cardsDealer.concat(this.state.cards.splice(0, 1))
    })

    if (scoreDealer === 21) {
      break;
    }
  }
}

有谁能够帮助我?

rossipedia在这篇文章中指出它很完美。

不要在循环中调用setState。 这里发生的事情恰恰是文档所指的:由于尚未应用暂挂状态更新,因此this.state返回先前的值。

循环调用setState仅更新状态1次

您的应用程序一直处于挂起状态的原因是this.state的值尚未更新,并且直到finishGame完成执行后才会更新,以及@ Jayce444在上面的注释中指出的某些错误逻辑。

我会在保留大部分逻辑的同时使用的解决方案是

finishGame = () => {
    // this is a copy of your array given I'm assuming its a 1D array and you can now mutate it
    const cardsDealer = [...this.state.cardsDealer];
    // if you chose to update scorePlayer you should declare it as let.
    const scorePlayer = this.state.cardsPlayer.reduce((a, b) => a + b);
    let scoreDealer = this.state.cardsDealer.reduce((a, b) => a + b);

    for (let i = 0; scoreDealer < 21; i++) {
        scoreDealer += cardsDealer.shift();

        // this will stop if card is >= to 21
        if (scoreDealer >= 21) {
            break;
        }
    }
    // this will set your cards to the new values after the loop is done running.
    this.setState({cardsDealer});
}

鉴于上述功能需要进行很多微调,我希望它可以为您提供一个良好的开端。 编码愉快!

暂无
暂无

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

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