Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在react中的下一个按键之前更改状态_Reactjs_Setinterval - Fatal编程技术网

Reactjs 在react中的下一个按键之前更改状态

Reactjs 在react中的下一个按键之前更改状态,reactjs,setinterval,Reactjs,Setinterval,我正在创建一个游戏,当你的生命值低于0时,它会在一个按键下打印一个div: “游戏结束:(_单击_继续”逐字逐句。我遇到了一个错误,字母会像ggggaaammmeeooovveerr一样打印多次 我设置了一个条件语句,其中如果状态gameOver为0,并且在一个keydown事件之后,它会激活setInterval,否则它不会。这在一定程度上解决了问题,但是,状态有时会在设置console.log(this.state.gameOver)后延迟一秒更改,它有时会在this.state.gameO

我正在创建一个游戏,当你的生命值低于0时,它会在一个按键下打印一个div:
“游戏结束:(_单击_继续”逐字逐句。我遇到了一个错误,字母会像ggggaaammmeeooovveerr一样打印多次

我设置了一个条件语句,其中如果状态gameOver为0,并且在一个keydown事件之后,它会激活setInterval,否则它不会。这在一定程度上解决了问题,但是,状态有时会在设置console.log(this.state.gameOver)后延迟一秒更改,它有时会在this.state.gameOver实际更改为1之前打印两次0。其他时候,它工作正常

if (this.state.gameOver===0){
 console.log(this.state.gameOver)
 var s1="Game_Over\n:(\nClick_to_continue..." 
 var v1 =0
 var b = document.getElementById("redButton")
 var arr1 = setInterval(function(){ 
 if(v1===0){b.innerText=""};b.innerText= b.innerText+s1[v1];v1+=1; 
 if(v1==s1.length){clearInterval(arr1)}}, 100)


 this.setState({gameOver:1})

}

有时它仍然会打印Ggaammee Ovveerr。

所以我所要做的就是设置一个条件语句,该语句取决于变量是true还是false。一旦触发setInterval函数,该变量就会变为false,这样更多的按键就不会导致对setInterval的多次调用

var check;

if (check!==false){ 

check=false;
var arr1 = setInterval(function(){
if(v1===0){b.innerText=""};
b.innerText= b.innerText+s1[v1];v1+=1; 
if(v1==s1.length){clearInterval(arr1)}}, 100)}
用鼠标单击屏幕后:

check=true;

记住一件事,react会在状态设置为setbut时重新呈现,但第一个keydown事件会触发上面的代码,这会将gameOver的状态更改为1,如果它确实重新渲染,为什么第二个keydown事件仍会输出等于零的gameOver?我很好奇为什么要设置div元素的内部文本而不使用ReactJS和它的DOM呈现方法来显示“游戏结束”文本?我不确定你如何将setTimeout函数与reactjs DOM元素结合起来,一次打印一个字母我同意@Padmika。你可以有一个setTimeout,它会一次更新一个字符的状态,然后使用react呈现而不是getElementById。