如果要满足条件,我想更改状态元素。为此,我尝试编写了一个函数,在该函数中有此条件,在满足条件时有新状态。但是如何调用此函数?我不需要像onClick或onChange这样的事件处理程序。但是怎么可能呢?
this.state = {
isPresidentVisible: false,
result: 0,
minutes: 3,
seconds: 0,
isQuizRunning: false,
isInputDisabled: true,
isGiveUpVisible: false,
}
}
handleChange = (e) => {
const index = presidents.findIndex(president => (
president.lastName.toLowerCase() === e.target.value.toLowerCase() || `${president.name.toLowerCase()} ${president.lastName.toLowerCase()}` === e.target.value.toLowerCase()));
if(index !== -1){
presidents[index].isPresidentVisible = true;
const isPresidentVisible = presidents[index].isPresidentVisible;
this.setState(({result}) => ({
isPresidentVisible,
result: result + 1
}))
e.target.value = '';
}
}
handleClick = () => {
this.setState({
isQuizRunning: true,
isInputDisabled: false,
isGiveUpVisible: true
})
this.interval = setInterval(() => {
const {seconds, minutes} = this.state
if(seconds > 0){
this.setState(({seconds}) => ({
seconds: seconds - 1
}))
}
if(seconds === 0){
if(minutes === 0){
this.handleEndGame();
} else{
this.setState(({minutes}) => ({
minutes: minutes - 1,
seconds: 59
}))
}
}
},1000)
}
handleEndGame = () => {
clearInterval(this.interval)
const isPresidentVisible = presidents.map(president => (president.isPresidentVisible = true))
this.setState({
isPresidentVisible,
isInputDisabled: true,
isGiveUpVisible: false,
})
}
我想提出条件:
checkCondition = () => {
const {result} = this.state;
if(result === presidents.length){
this.handleEndGame();
}
}