【发布时间】: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