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