【问题标题】:On React hook component unmount, unable to get updated state variable value在 React 钩子组件卸载时,无法获取更新的状态变量值
【发布时间】:2020-09-14 19:56:54
【问题描述】:

点击“点击我”按钮后,我的计数值正在更新。现在,如果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>
    );
}

【问题讨论】:

    标签: reactjs react-hooks use-effect


    【解决方案1】:

    当您在useEffect 中设置清理功能时,您正在对count 的原始值形成一个闭包。这意味着即使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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-01
      • 2021-02-04
      • 2019-08-30
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      相关资源
      最近更新 更多