关于react中setState的异步及同步

容我先记录一些开发中遇到的有趣的东西(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循环和逻辑运算符有一定的了解(坏笑)

进入正题,最近的开发中遇到了这样的情况:


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

???我不是设置为true了吗?答案是因为setState是异步的操作,在console的时候state的值还没有改变如果代码改为:

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

 这样的话console也处于异步队列中  并且排在setState后面,所以就会输出true。那么有没有更简单的方法呢?答案是有的:

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

over

发布了47 篇原创文章 · 获赞 38 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq8241994/article/details/103374062