[英]On React hook component unmount, unable to get updated state variable value
After clicking on "Click me" button my count value is updating.单击“单击我”按钮后,我的计数值正在更新。 Now I have to Do Something if
count
is grater then 0
before my component unmount.现在我必须做一些事情,如果在我的组件卸载之前
count
大于0
。
But I have noticed during debugger count
value is always 0
.但我注意到调试器
count
数值始终为0
。 While I was expecting count
should be grater then 0
if I clicked multiple times.虽然我期望
count
应该大于0
如果我多次点击。
Please help me, how to get updated value during component unmount.请帮助我,如何在组件卸载期间获取更新的值。 Thanks
谢谢
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>
);
}
You are forming a closure over the original value of count
when you set up your cleanup function in the useEffect
.当您在
useEffect
设置清理函数时,您正在对count
的原始值形成一个闭包。 That means that even as the value of count
updates in the state, the value of count stays as 0
in the cleanup function.这意味着即使状态中
count
的值更新, count
的值在清理函数中仍保持为0
。
To avoid this, you need to add count
to the array of dependencies for your useEffect
.为避免这种情况,您需要将
count
添加到useEffect
的依赖项数组。 That way, when count
updates in state, and the component re-renders, the cleanup function also updates with the latest value of count
.这样,当
count
更新 state 并且组件重新渲染时,cleanup 函数也会更新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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.