日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

關于react?useState更新異步問題_React

作者:Richard?Yates?Boy ? 更新時間: 2022-10-02 編程語言

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

欄目分類
最近更新