【问题标题】:React Hooks, setTimeOut to set State to falseReact Hooks, setTimeOut 将 State 设置为 false
【发布时间】:2021-02-24 14:11:17
【问题描述】:
我有这种情况
const [showAlertLink, setShowAlertLink] = useState(false);
const handleClick = () => {
setShowAlertLink(true);
};
<Button disableRipple onClick={handleClick}>
{!!showAlertLink && <Alert icon={<CheckIcon fontSize="inherit" />} onClose={() => setShowAlertLink(false)}>{t(`alert_link_copied`)}</Alert>}
目前,如果我单击图标,我可以关闭警报。
例如,我怎样才能使此警报以SetTimeout 持续时间 2 秒自动关闭?
【问题讨论】:
标签:
javascript
reactjs
react-hooks
settimeout
use-state
【解决方案1】:
你可以使用useEffect:
useEffect(() => {
let timeout
if (showAlertLink) {
timeout = setTimeout(() => setShowAlertLink(false), 2000);
}
return () => clearTimeout(timeout);
}, [showAlertLink]);
当showAlertLink 值改变时触发。如果是true,它会设置一个超时时间,在 2 秒内将其设置为 false (2000)。
请注意,您始终返回效果以清除超时(以确保您不会收到tried to update state of an unmounted component)错误。
如果你使用的是打字稿,你可以像这样输入timeout:
let timeout: ReturnType<typeof setTimeout>;