網站首頁 編程語言 正文
react useState更新異步
當我們使用react中useState這個hook時候,如下
const [page, setPage] = useState(1);
const handlerClick = (e)=>{
?? ?setPage(e.current);
?? ?console.log(page);
}
當我打印page時候,此時page還是1,因為useState的更新是異步的,這和react的機制有關,要解決這個可以這樣做
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
? ? ? });
//調用
setPage(e.current);
funcqq()
自定義hook(第二種方式)
function useCurrentValue(value) {
? ? const ref = useRef(value);
? ? useEffect(() => {
? ? ? ref.current = value;
? ? }, [value]);
? ? return ref;
}
//調用
?const log = () => {
? ? setCount(count + 1);
? ? setTimeout(() => {
? ? ? console.log(currentCount.current);
? ? }, 3000);
? };
3.使用useRef替代useState,第三種方式在自定義hook第二種方式里面已經體現了
4.使用useEffect,在自定義hook第二種方式里面已經體現了
記useState異步更新小坑
問題:
在hooks中,修改狀態的是通過useState返回的修改函數實現的.它的功能類似于class組件中的this.setState().而且,這兩種方式都是異步的.可是this.setState()是有回調函數的,那useState()呢?
問題點
它異步且沒有回調函數
const [count,setCount] = useState(1)
useEffect(()=> {
setCount(2,()=>{
console.log('測試hooks的回調');
})
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().”
是不支持回調函數的形式的。因為setCount是異步的,所以打印count是在改變count之前的。
如果我們想要在打印的時候就拿到最新的值,那么我們可以通過setCount的第二個參數指定依賴項
const [count,setCount] = useState(1)
useEffect(()=> {
setCount(2)
console.log(count);
},[count])
當count發生變化的時候,useEffect就會再次相應,但是這樣就會有個問題,當count從1變為2的時候useEffect的回調函數會再次執行,就會分別打印1,2兩次。
useEffect(()=> {
let currentValue = null
setCount((preVal)=>{
currentValue=preVal
return 2
})
if(currentValue!==count){
console.log(count);
}
},[count])
通過添加判斷條件,我們可以讓想要執行的代碼只執行一次
原文鏈接:https://blog.csdn.net/weixin_44046355/article/details/123923149
相關推薦
- 2023-04-24 Python?相對路徑和絕對路徑及寫法演示_python
- 2023-03-02 SQLServer?清理日志的實現_MsSql
- 2022-07-12 Springboot Druid 啟動報錯:Failed to configure a DataSo
- 2022-09-16 Python中的?No?Module?named?***問題及解決_python
- 2022-12-26 C#操作xml文件之Linq?To?Xml詳解_C#教程
- 2022-07-25 C++文件的操作及小實驗示例代碼詳解_C 語言
- 2022-04-12 【debug】PytorchStreamReader failed reading zip arch
- 2022-12-09 python中為main方法傳參問題_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支