簡體   English   中英

在功能組件中反應 useState 不會立即更新屬性值

[英]React useState in functional components not updating the property values immediately

react useState 鈎子不會更新屬性值並顯示舊值,即使在一段時間后訪問它也是如此。 我知道這是異步更新,但最終它應該更新值。 這是我的代碼:

const [ currentRowIndex, setCurrentRowIndex] = useState(0);
    React.useEffect(() => { 
        console.log('Index from useEffect: ',currentRowIndex);
        setCurrentRowIndex(currentRowIndex);}, [currentRowIndex]);
..
..
..
 const handleClick = (event, index) => {

        console.log('Index after click: ',index);
        setCurrentRowIndex(index);

        setTimeout(function(){ 
            console.log('Index in timeout: ',currentRowIndex);
         }, 3000);

        console.log('Index after updating: ',currentRowIndex);

    };

Output 從控制台:

Index after click:  4
Index after updating:  0
Index from useEffect:  4
Index in timeout:  0

console.log('Index after updating: ',currentRowIndex); 這給出了 0,因為沒有確認當瀏覽器執行此 state 時已經更新。

當您在更新完成后看到索引值時,您只需在 useEffects 中打印索引,其中包含[currentRowIndex]的依賴項列表,然后它表明您的索引正在正確更新。

如果您可以提供信息,您究竟想用這個更新的值做什么,那么它將幫助我們更好地了解問題。

一切都按預期發生,每次將組件渲染為框架時都要考慮一下。

At the time you call handleClick the currentRowIndex is 0, you pass 0 to your setTimeout and you get 0 printed because that function remembers the currentRowIndex as 0 at this specific render, that function is not changed when the state updates.

如果您在 Text 組件中渲染 currentRowIndex,您將看到它確實更新了,因為新渲染具有更新的 state。

您可以在 handleClick 之外打印它並查看每個渲染上的 state 值。

 console.log('Index: ',currentRowIndex);

 const handleClick = (event, index) => {
       ...
    };

暫無
暫無

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

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