您现在的位置是:网站首页> 编程资料编程资料

关于react useState更新异步问题_React_

2023-05-24 362人已围观

简介 关于react useState更新异步问题_React_

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

通过添加判断条件,我们可以让想要执行的代码只执行一次

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

-六神源码网