在React中,为什么setState()优先于setTimeout执行?

时间:2018-08-24 02:39:38

标签: javascript reactjs

在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

1 个答案:

答案 0 :(得分:1)

无需使用setTimeout。 setState函数确实支持回调函数。

setState(updater[, callback])