在React Hook组件卸载后,无法获取更新的状态变量值

时间:2020-09-14 11:41:30

标签: reactjs react-hooks use-effect

点击“点击我”按钮后,我的计数值正在更新。现在,如果count比我要拆卸组件前的0好,那么我就必须做些事情。

但是我注意到在调试器期间count的值始终为0。我原本希望count会比单击0时好些,如果我单击了多次。

请帮助我,如何在组件卸载期间获取更新的值。谢谢

import React, { useState, useEffect } from 'react';

function Example() {
    const [count, setCount] = useState(0);

    useEffect(() => {
    //ComponentDidMount 

    return(()=>{                        
        //componentWillUnmount
        alert(count); //count 0  
        if(count){
            //Do Something                
        }           
    })        
    },[]);

    useEffect(() => {
    document.title = `You clicked ${count} times`;        
    });

    return (
    <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>
        Click me
        </button>
    </div>
    );
}

1 个答案:

答案 0 :(得分:3)

count中设置清理功能时,您正在封闭useEffect的原始值。这意味着即使在状态中count的值更新时,在清除功能中count的值仍保持为0

为避免这种情况,您需要向count的依赖项数组中添加useEffect。这样,当count的状态更新并且组件重新渲染时,清除功能也会更新为count的最新值。

useEffect(() => {
  return (()=> {                        
    alert(count); // this will now be latest value of count on unmount
    if(count) {
      // Do Something                
    }           
  })        
}, [count]); // add is now a dependency of useEffect