ReactJS-调用了render,但是DOM没有更新 [英] ReactJS - render called, but DOM not updated
问题描述
这件事发生在我身上几次。我一直设法解决这个问题,但是仍然很想了解为什么会发生这种情况以及我错过了什么。
基本上,如果我的身体有病, render
方法,该方法指定我的 div
的类:
let divClass = this.state.renderCondition吗? '红蓝';
默认情况下,我在州内设置 renderCondition
如果我随后在按钮上定义了 onClick
处理程序(如下所示),然后单击按钮,而渲染 IS 时,DOM 不被更新。也就是说,班级没有改变。
onClickCompile:function(){
this.setState({renderCondition:true},function( ){
syncSlowFunction();
});
}
这似乎与运行慢速同步代码有关,如果代码快速简便地对DOM IS 进行了适当的更新。
如果我将调用包装到 synchronousSlowFunction
在500毫秒的超时时间内,一切正常。但是,我想了解自己被误解了的原因,因此我不需要此技巧。码?我可能是错的,但这似乎是按钮的onClick侦听器设置错误。
请确保定义的onClick回调不带(),即
< button onClick = {this.something} />
而不是:
< button onClick = {this.something()} />
发布更多代码,以便获得更好(更大)的图片
This has happened to me a few times. I have always managed to work around the issue, yet I am still intrigued to understand why this happens, and what I have missed.
Essentially if I have a condition within my render
method which specifies the class for my div
:
let divClass = this.state.renderCondition ? 'red' : 'blue';
By default I set renderCondition
within my state to false.
If I then define an onClick
handler on a button (as follows), and click the button, whilst render IS called, the DOM is NOT updated. That is to say the class does not change.
onClickCompile: function() {
this.setState({renderCondition: true}, function() {
synchronousSlowFunction();
});
}
This seems to have something to do with running slow synchronous code in that if the code is quick and simple the DOM IS updated appropriately.
If I wrap the call to synchronousSlowFunction
in a 500 millisecond timeout, everything works as expected. I would however like to understand what I have misunderstood such that I do not need this hack.
Can you share the button onClick code? I might be wrong but this looks like an incorrectly set button onClick listener.
Make sure that onClick callback is defined without (), i.e.
<button onClick={this.something} />
instead of:
<button onClick={this.something()} />
Post more code so we can get a better (bigger) picture
这篇关于ReactJS-调用了render,但是DOM没有更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!