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);

};

相关推荐
明仔的阳光午后26 分钟前
React 入门 02:从单页面应用到多页面应用
前端·react.js·前端框架
.生产的驴29 分钟前
React 页面路由ReactRouter 路由跳转 参数传递 路由配置 嵌套路由
前端·javascript·react.js·前端框架·json·ecmascript·html5
非凡ghost30 分钟前
批量转双层PDF(可识别各种语言) 中文绿色版
前端·windows·pdf·计算机外设·软件需求
苏卫苏卫苏卫32 分钟前
【码源】智能无人仓库管理系统(详细码源下~基于React+TypeScript+Vite):
前端·react.js·typescript·vite·项目设计·智能无人仓库管理系统·码源
打小就很皮...32 分钟前
PDF 下载弹窗 content 区域可行性方案
前端·javascript·pdf
Felicity_Gao3 小时前
uni-app VOD 与 COS 选型、开发笔记
前端·笔记·uni-app
我狸才不是赔钱货5 小时前
前端技术栈全景图:从HTML到现代框架的演进之路
前端·html
百花~5 小时前
前端三剑客之一 HTML~
前端·html
lang201509286 小时前
Spring远程调用与Web服务全解析
java·前端·spring
孤狼warrior8 小时前
爬虫进阶 JS逆向基础超详细,解锁加密数据
javascript·爬虫