[英]How to check current state inside component by loop in react?
I mean about function tillMaxWin, when i run it, component chceck state.points, draw again but doesnt uptade state.我的意思是关于功能直到MaxWin,当我运行它时,组件检查state.points,再次绘制但不更新状态。 I want to draw till points === 6 but i dont know how to fix it in React, how to uptade state inside component tillMaxWinn,check if this.state.points is < 6 and if it is true draw again till state.points is 6. Any idea?我想画到点数 === 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();
}
};
The issue you're never advancing this.state.points.你永远不会推进 this.state.points 的问题。 Try this:尝试这个:
tillMaxWin = () => {
this.generateDrawedNumbers();
this.compareNumbers();
while (this.state.points < 6) {
this.setState((prevState) => ({ points: prevState.points + 1 }), () => this.tillMaxWin();
}
}
This should trigger the function again once the state is set.一旦设置了状态,这应该再次触发该功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.