[英]why does this code change the string but again revert back to original state
[英]Can I change the state for given time and then revert it back to the original state using settimeout
我想將值設置為 true 一秒鍾,之后它將使用 settimeout 恢復為 false 但卡住了。 這是我的代碼:
const [value, setValue] = useState(false)
const handleClick = () => {
setTimeout(() => {
setValue(!value)
console.log(value);
},1000);
console.log(value);
}
const [value, setValue] = useState(false);
const timeoutId = useRef(null);
const handleClick = () => {
// clear existing timeout
clearTimeout(timeoutId.current);
// set the value to true
setValue(true);
// revert the value to false after 1s
timeoutId.current = setTimeout(() => setValue(false), 1000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.