react useState异步问题

1.

useState执行后 不能立马拿到新的数据,下次更新绘图就可以拿到了

然后当执行完第一次render时候,比如去点击按钮啥的执行某个方法这个时候就可以拿到数据了

例子:

const UseState = () => {

// 函数组件中没有this

const [count, setCount] = useState(0)

const add = () => {

let newCount = count

console.log('value1', count); // 0

setCount( newCount+= 1)

console.log('value2', count); // 0

query()

}

const query = () => {

console.log('query函数中:', count); // 0

}

return (

{count}

增加

)
}

解决方法:
1)可以将count的新值通过函数传参的方式传入query函数;
// 改写add和query函数;

const add = () => {

let newCount = count

console.log('value1', count);

setCount( newCount+= 1)

console.log('value2', count);

query(newCount)

}

const query = (count) => {

console.log('query函数中:', count);

}

2)在useEffect中调用query函数,因为在useEffect中,组件dom已经更新完毕,可以拿到count的最新值;(缺点:每次count值改变,都会触发useEffect,从而执行query函数;)

// 组件每次渲染之后执行的操作,执行该操作时dom都已经更新完毕

useEffect(()=>{

// 1、可在此处拿到count更新后的值

console.log('value3', count);

query()

}, [count])

const add = () => {

let newCount = count

console.log('value1', count);

setCount( newCount+= 1)

console.log('value2', count);

}

const query = () => {

console.log('query函数中:', count);

}

3)通过useRef()定义一个可变的ref变量,通过current属性保存count可变值,从而在count更新后,通过ref的current属性拿到更新后的count值;注意:调用query函数时需要加上setTimeout()进行调用;

// 定义一个可变的countRef对象,该对象的current属性被初始化为传入的参数count;

const countRef = useRef(count)

// 在countRef.current属性中保存一个可变值count的盒子;

countRef.current = count

const add = () => {

let newCount = count

console.log('value1', count);

setCount( newCount+= 1)

console.log('value2', count);

setTimeout(() => query(), 0);

}

const query = () => {

console.log('query函数中:', countRef.current);

}

2.

下次更新绘图就可以拿到了

然后当执行完第一次render时候,比如去点击按钮啥的执行某个方法这个时候就可以拿到新的数据了

例子:

const [init, setInit] = useState()

const inti = async () => {

setInit(true)

};

useEffect(() => {

init();

}, []);

const fn = async () => {

console.log(881, init);

};

相关推荐
PineappleCoder4 小时前
性能数据别再瞎轮询了!PerformanceObserver 异步捕获 LCP/CLS,不卡主线程
前端·性能优化
PineappleCoder4 小时前
告别字体闪烁 / 首屏卡顿!preload 让关键资源 “高优先级” 提前到
前端·性能优化
m0_471199635 小时前
【vue】通俗详解package-lock文件的作用
前端·javascript·vue.js
GIS之路5 小时前
GDAL 读取KML数据
前端
今天不要写bug5 小时前
vue项目基于vue-cropper实现图片裁剪与图片压缩
前端·javascript·vue.js·typescript
用户47949283569156 小时前
记住这张时间线图,你再也不会乱用 useEffect / useLayoutEffect
前端·react.js
咬人喵喵6 小时前
14 类圣诞核心 SVG 交互方案拆解(附案例 + 资源)
开发语言·前端·javascript
问君能有几多愁~6 小时前
C++ 日志实现
java·前端·c++
咬人喵喵6 小时前
CSS 盒子模型:万物皆是盒子
前端·css