簡體   English   中英

反應掛鈎中的另一個卸載useEffect不會影響狀態更改

[英]Change of state is not getting affected in another unmount useEffect in react hooks

新的反應鈎子。

// create as state using useState
  const [clearSelected,setClearSelected] = useState(true);

//clearSelected is changed to false
 setClearSelected(false);

由於鈎子中沒有回調函數,我等到clearSelected變為false然后移動到另一頁面

 useEffect(()=>{
//clear selected is set to false and then redirection to another page is done

    if(clearSelected === false){

      history.push('/nextPage');
    }
  },[clearSelected]);
//clears the redux state on unmount
useEffect(()=>{ 
    return (()=>{
       //should not go inside when clearSelected is false 
      if(clearSelected){
       //clear the redux state
        actions.items([], false);
      }
    })
  },[]);

即使在clearSelected變為false之后進行重定向,redux狀態也會被清除。

我在上面的unmount hook中打印了clearSelected。這是真的。

我可以知道它為什么不起作用。 謝謝。

你基本上在第二個useEffect創建一個閉包,它有效地鎖定了狀態的初始值( true ):

useEffect(()=>{ 
    return (()=>{ // closure that holds initial value of the `clearSelected`
      // ...
    })
  },[]);

如果要保留對閉包中當前狀態的訪問權限,請考慮使用useRef存儲對它的引用。

所以,像這樣:

const [clearSelected, setClearSelected] = useState(true);
const clearSelectedRef = useRef(clearSelected);

useEffect(() => {
    clearSelectedRef.current = clearSelected;
    if (clearSelected === false) {
        history.push('/nextPage');
    }
}, [clearSelected]);

useEffect(() => {
    return (() => {
        //should not go inside when clearSelected is false 
        if (clearSelectedRef.current) {
            //clear the redux state
            actions.items([], false);
        }
    })
}, []);

clearSelected之所以為假是因為關閉。

你的功能

()=>{
  //should not go inside when clearSelected is false 
  if(clearSelected){
    //clear the redux state
    actions.items([], false);
  }
}

安裝時獲取clearSelected狀態。 您可以在此處閱讀有關閉包的更多信息。

您將需要使用useRef及其current值來使代碼正常工作。

此外, 這里是一個指導useEffect丹Abromov。 它將幫助您了解useEffect

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM