var SubOne = React.createClass({
getInitialState(){
return {
current : 0
};
},
render() {
var that = this;
var list = [
1111,2222,3333,444
];
var createItem = function(itemText, index) {
return <li key={index} data-index={index} onClick={that._handleClick}>{itemText}</li>;
};
return <ul ref="list">{list.map(createItem)}</ul>;
},
componentDidMount(){
var that = this;
setTimeout(function(){
that._handleClick();
}, 2000);
},
_handleClick(){
console.log("before setState");
this.setState({
current : 0
},function(){
console.log("setState callback");
});
console.log("after setState");
}
});
React.render(<SubOne />, document.getElementById("example"));
结果是:
setTimeout 调用:
设置状态之前 设置状态回调 设置状态后
onclick 调用:
设置状态之前 设置状态后 setState回调
为什么执行顺序不同?
最佳答案
这与React的批量更新机制有关。我对这个话题并不擅长,所以我不能给你一个明确的答案,但也许这里的讨论会给你带来一些启发:) https://groups.google.com/forum/#!topic/reactjs/LkTihnf6Ey8
关于javascript - React setState回调执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32494600/