簡體   English   中英

如何在反應中通過循環檢查組件內部的當前狀態?

[英]How to check current state inside component by loop in react?

我的意思是關於功能直到MaxWin,當我運行它時,組件檢查state.points,再次繪制但不更新狀態。 我想畫到點數 === 6 但我不知道如何在 React 中修復它,如何在組件內更新狀態直到 MaxWinn,檢查 this.state.points 是否 < 6,如果它是真的再次繪制直到 state.points是 6. 有什么想法嗎?

class App extends Component {
  state = {
    MyNumbers: [],
    DrawedNumbers: [],
    ofHowMany: 49,
    howMany: 6,
    points: 0,
    numberOfDraws: 0
  };

  drawMyNumbers = () => {
    const numbers = [];
    for (let i = 0; i < this.state.howMany; i++) {
      let number = Math.floor(Math.random() * this.state.ofHowMany + 1);
      while (numbers.includes(number)) {
        number = Math.floor(Math.random() * this.state.ofHowMany + 1);
      }
      numbers.push(number);
    }
    this.setState({
      MyNumbers: numbers.sort(sortingUp)
    });
  };

  generateDrawedNumbers = () => {
    numberOfDraws = numberOfDraws + 1;
    const numbers = [];
    for (let i = 0; i < this.state.howMany; i++) {
      let number = Math.floor(Math.random() * this.state.ofHowMany + 1);
      while (numbers.includes(number)) {
        number = Math.floor(Math.random() * this.state.ofHowMany + 1);
      }
      numbers.push(number);
    }
    this.setState({
      DrawedNumbers: numbers.sort(sortingUp)
    });
  };

  componentDidUpdate() {
    this.compareNumbers();
    if (points !== this.state.points) {
      this.setState({ points: points });
    }

    if (numberOfDraws !== this.state.numberOfDraws) {
      this.setState((prevState, props) => ({
        numberOfDraws: prevState.numberOfDraws + 1
      }));
    } else return;
  }

  compareNumbers = () => {
    points = 0;
    for (let i = 0; i < this.state.howMany; i++) {
      for (let j = 0; j < this.state.howMany; j++) {
        if (this.state.MyNumbers[i] === this.state.DrawedNumbers[j]) {
          points = points + 1;

          console.log(
            "trafione" +
              this.state.MyNumbers[i] +
              " " +
              this.state.DrawedNumbers[j] +
              " Liczba losowań" +
              numberOfDraws
          );

          console.log(points);
        } else {
          console.log("nie");
        }
      }
    }
    return points;
  };

  tillMaxWin = () => {
    this.generateDrawedNumbers();
    this.compareNumbers();
    points = this.state.points;
    while (points < 6) {
      console.log("Points: " + points);
      this.tillMaxWin();
    }
  };

你永遠不會推進 this.state.points 的問題。 嘗試這個:

tillMaxWin = () => {
  this.generateDrawedNumbers();
  this.compareNumbers();
  while (this.state.points < 6) {
    this.setState((prevState) => ({ points: prevState.points + 1 }), () => this.tillMaxWin();
  }
}

一旦設置了狀態,這應該再次觸發該功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM