我试图在之前出现“加载”消息在React中进行耗时的操作。我试过这个:
var LoadingExample1 = React.createClass({
getInitialState: function () {
return {message: ""};
},
render: function () {
return (
<div>
<div>{this.state.message}</div>
<button onClick={this.doWork}>Solve</button>
</div>
)
},
doWork: function () {
this.setState({message: "Loading..."});
for (var i = 0; i < 1000000000; i++) {
;
}
this.setState({message: "Done."});
}
});
React.renderComponent(
<LoadingExample1 />,
document.getElementById("example1")
);
但似乎只有在操作完成后才更新UI,这为时已晚。我也尝试过使用setState回调,但结果是一样的:
var LoadingExample2 = React.createClass({
getInitialState: function () {
return {message: ""};
},
render: function () {
return (
<div>
<div>{this.state.message}</div>
<button onClick={this.doWork}>Solve</button>
</div>
)
},
doWork: function () {
this.setState({message: "Loading..."}, function () {
for (var i = 0; i < 1000000000; i++) {
;
}
this.setState({message: "Done."});
});
}
});
React.renderComponent(
<LoadingExample2 />,
document.getElementById("example2")
);
有关下一步尝试的建议吗?
答案 0 :(得分:3)
这就是我要做的。如果有更好的方法,我有兴趣听听。
var LoadingExample3 = React.createClass({
getInitialState: function () {
return {message: ""};
},
render: function () {
return (
<div>
<div>{this.state.message}</div>
<button onClick={this.doWork}>Solve</button>
</div>
)
},
doWork: function () {
this.setState({message: "Loading..."});
this.doWorkAsync();
},
doWorkAsync: function () {
var self = this;
setTimeout(function() {
for (var i = 0; i < 1000000000; i++) {
;
}
self.setState({message: "Done."});
}, 0); // timeout of 0 ms means "run at the end of the current event loop"
}
});
React.renderComponent(
<LoadingExample3 />,
document.getElementById("example1")
);