網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
react useState更新異步
當(dāng)我們使用react中useState這個(gè)hook時(shí)候,如下
const [page, setPage] = useState(1);
const handlerClick = (e)=>{
?? ?setPage(e.current);
?? ?console.log(page);
}
當(dāng)我打印page時(shí)候,此時(shí)page還是1,因?yàn)閡seState的更新是異步的,這和react的機(jī)制有關(guān),要解決這個(gè)可以這樣做
1.使用useState的返回值
?setPage(e.current);
? ? ? ? setPage(prevFoo => {
? ? ? ? ? ? console.log('page===========',prevFoo);//page=========== 2
? ? ? ? ? ? return prevFoo;
?});
2.自定義hook(第一種方式)
? ? const useSyncCallback = callback => {
? ? ? ? const [proxyState, setProxyState] = useState({ current: false });
? ? ? ? const Func = useCallback(() => {
? ? ? ? ? setProxyState({ current: true });
? ? ? ? }, [proxyState]);
? ? ? ? useEffect(() => {
? ? ? ? ? if (proxyState.current === true) {
? ? ? ? ? ? setProxyState({ current: false });
? ? ? ? ? }
? ? ? ? }, [proxyState]);
? ? ? ? useEffect(() => {
? ? ? ? ? proxyState.current && callback();
? ? ? ? });
? ? ? ? return Func;
? ? ? };
? ? ? const funcqq = useSyncCallback(() => {
? ? ? ? console.log('page===========',page);//page=========== 2
? ? ? });
//調(diào)用
setPage(e.current);
funcqq()
自定義hook(第二種方式)
function useCurrentValue(value) {
? ? const ref = useRef(value);
? ? useEffect(() => {
? ? ? ref.current = value;
? ? }, [value]);
? ? return ref;
}
//調(diào)用
?const log = () => {
? ? setCount(count + 1);
? ? setTimeout(() => {
? ? ? console.log(currentCount.current);
? ? }, 3000);
? };
3.使用useRef替代useState,第三種方式在自定義hook第二種方式里面已經(jīng)體現(xiàn)了
4.使用useEffect,在自定義hook第二種方式里面已經(jīng)體現(xiàn)了
記useState異步更新小坑
問(wèn)題:
在hooks中,修改狀態(tài)的是通過(guò)useState返回的修改函數(shù)實(shí)現(xiàn)的.它的功能類似于class組件中的this.setState().而且,這兩種方式都是異步的.可是this.setState()是有回調(diào)函數(shù)的,那useState()呢?
問(wèn)題點(diǎn)
它異步且沒(méi)有回調(diào)函數(shù)
const [count,setCount] = useState(1)
useEffect(()=> {
setCount(2,()=>{
console.log('測(cè)試hooks的回調(diào)');
})
console.log(count);
},[])
可以看到提示 “State updates from the useState() and useReducer() Hooks don’t support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().”
是不支持回調(diào)函數(shù)的形式的。因?yàn)閟etCount是異步的,所以打印count是在改變count之前的。
如果我們想要在打印的時(shí)候就拿到最新的值,那么我們可以通過(guò)setCount的第二個(gè)參數(shù)指定依賴項(xiàng)
const [count,setCount] = useState(1)
useEffect(()=> {
setCount(2)
console.log(count);
},[count])
當(dāng)count發(fā)生變化的時(shí)候,useEffect就會(huì)再次相應(yīng),但是這樣就會(huì)有個(gè)問(wèn)題,當(dāng)count從1變?yōu)?的時(shí)候useEffect的回調(diào)函數(shù)會(huì)再次執(zhí)行,就會(huì)分別打印1,2兩次。
useEffect(()=> {
let currentValue = null
setCount((preVal)=>{
currentValue=preVal
return 2
})
if(currentValue!==count){
console.log(count);
}
},[count])
通過(guò)添加判斷條件,我們可以讓想要執(zhí)行的代碼只執(zhí)行一次
原文鏈接:https://blog.csdn.net/weixin_44046355/article/details/123923149
相關(guān)推薦
- 2022-01-31 nginx中的超時(shí)設(shè)置,請(qǐng)求超時(shí)、響應(yīng)等待超時(shí)等
- 2022-03-17 c++實(shí)現(xiàn)一個(gè)簡(jiǎn)易的網(wǎng)絡(luò)緩沖區(qū)的實(shí)踐_C 語(yǔ)言
- 2022-04-24 教你使用mongoose實(shí)現(xiàn)多集合關(guān)聯(lián)查詢_MongoDB
- 2022-06-06 自定義overflow產(chǎn)生的滾動(dòng)條樣式設(shè)置
- 2022-01-31 element-ui upload組件 上傳文件類型限制
- 2022-09-25 Clion配置STM32開(kāi)發(fā)環(huán)境printf函數(shù)打印浮點(diǎn)數(shù)快速設(shè)置方法
- 2022-05-12 uni-app混合原生安卓開(kāi)發(fā)
- 2023-01-08 Python?flask與fastapi性能測(cè)試方法介紹_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支