1

单击“单击我”按钮后,我的计数值正在更新。现在我必须在我的组件卸载之前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>
    );
}
4

1 回答 1

4

当您countuseEffect. 这意味着即使count状态中的更新值,计数的值仍0与清理函数中一样。

为避免这种情况,您需要countuseEffect. 这样,当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 
于 2020-09-14T11:51:35.183 回答