About react in setState asynchronous and synchronous

First let me record some of the interesting things encountered in the development of (O (∩_∩) O):

console.log(typeof ('' || null));
console.log(typeof (null || ''));
console.log(typeof (null && ''));
console.log(typeof ('' && null));
// 这个需要对逻辑运算符有一定的了解

function r(n, t) { 
   for (var r = -1, e = null == n ? 0 : n.length; ++r < e && false !== t(n[r], r, n);); 
   return n 
}
// 摘自lodash源码 需要对for循环和逻辑运算符有一定的了解(坏笑)

Entered, recent developments encountered such a situation:


this.setState({
    isLoading: true,
})
console.log(this.state.isLoading);// 输出为false

? ? ? I'm not set to true yet? The answer is because setState is asynchronous operations, the value of the console when the state has not changed if the code to read:

this.setState({
    isLoading: true,
})
setTimeout(()=>{console.log(this.state.isLoading);},0)//输出为true

 Also in this case console asynchronous queue and at the back setState, it will output true. Is there an easier way to do that? The answer is yes:

this.setState({
    isLoading: true,
},() => console.log(this.state.isLoading))// true
// setState接收第二个参数,表示当赋值完毕后进行的操作,即回调

 

over

Published 47 original articles · won praise 38 · views 60000 +

Guess you like

Origin blog.csdn.net/qq8241994/article/details/103374062