当用户单击某个按钮时,我正在调用功能createSession
。防止批量更新中的setState
在createSession
我运行:
this.setState({divClass: 'show'}, function() {
...computationally intensive and async stuff
})
通过改变this.state.divClass
到'show'
的DOM应该被重新绘制,并显示一个div以前有一类'hide'
我已经掉了在渲染函数中使用console.log来确保setState实际上是在它执行other stuff
之前重新渲染的。即使控制台显示组件已重新渲染,视图也不会更改,除非其他内容完成。
我很困惑的是组件在调用回调之前被重新渲染,但只有在回调完成之后才会显示更改。
我使用的是13.0版本的阵营
下面是一些代码(抱歉,这是咖啡):
crypto = require('crypto')
Component = React.createClass({
render: ->
<button onClick={@showDiv}>Show Div</button>
<div className={@state.divDisplay}>
Wooo
</div>
getInitialState: -> {
divDisplay: 'hide'
}
showDiv: ->
@setState({divDisplay: 'show'}, ->
salt = crypto.randomBytes(16).toString('hex')
# this call is not really sync
crypto.pbkdf2('password', salt, 10000, 32, 'sha1', (error, hash) ->
console.log error, hash
)
)
})
UPDATE(和个人解决方案)
我发现这个问题并不是React将其更新分配给状态 - 我使用的密码哈希库运行同步。该库会阻止用户界面更新。所以即使渲染调用将console.log状态改变了,用户界面也无法更新。
我结束了使用网络工作者在后台散列密码。这使得其余的UI可以照常运行。
请包含足够的代码,以便我们重现问题。 – FakeRainBrigand 2015-03-31 05:24:21