在React中,setState()
是异步函数,而setTimeout()
也是异步函数(有人认为,setState()
可能是同步函数?),
为什么setState()
比setTimeout()
优先执行?
componentDidMount(){
this.setState({val: this.state.val + 1}, ()=>{
console.log("In callback " + this.state.val);
});
console.log("Direct call " + this.state.val);
setTimeout(()=>{
console.log("begin of setTimeout" + this.state.val);
this.setState({val: this.state.val + 1}, ()=>{
console.log("setTimeout setState callback " + this.state.val);
});
setTimeout(()=>{
console.log("setTimeout of settimeout " + this.state.val);
}, 0);
console.log("end of setTimeout " + this.state.val);
}, 0);
}
> Direct call 0
> In callback 1
> begin of setTimeout 1
> setTimeout setState callback 2
> end of setTimeout 2
> setTimeout of settimeout 2
答案 0 :(得分:1)
无需使用setTimeout。 setState函数确实支持回调函数。
setState(updater[, callback])