我可以从 setTimeout() 调用 setState() 吗?
Can I call setState() from a setTimeout()?
我的组件中有以下代码:
- 我通过使用
setPosition(-0.08)
调用 setState 来开始反弹效果
- 然后我使用 ref 存储
setTimeout
并在 350 毫秒后调用 setPosition(0)
。
function changeImage(dir) {
const isBouncing = useRef(false);
const bounceTimeout = useRef(null);
// ... some other code
if (dir === 'LEFT' && selected === 0) {
isBouncing.current = true;
setPosition(-0.08);
bounceTimeout.current = setTimeout(()=> {
isBouncing.current = false;
setPosition(0);
}, 350);
return;
}
}
它按预期工作!
问题
我有什么理由不应该这样做(从
setTimeout
)?
您可以从 setTimeout
呼叫 setState
。例如,这是实现动画的方法之一。
但在您的情况下,您应该将代码移至 useEffect
挂钩,否则可能会导致副作用。
并且您还需要清除卸载超时
useEffect(() => {
return () => {
if (bounceTimeout.current !== null) {
clearTimeout(bounceTimeout.current)
}
}
}, [])
我的组件中有以下代码:
- 我通过使用
setPosition(-0.08)
调用 setState 来开始反弹效果
- 然后我使用 ref 存储
setTimeout
并在 350 毫秒后调用setPosition(0)
。
function changeImage(dir) {
const isBouncing = useRef(false);
const bounceTimeout = useRef(null);
// ... some other code
if (dir === 'LEFT' && selected === 0) {
isBouncing.current = true;
setPosition(-0.08);
bounceTimeout.current = setTimeout(()=> {
isBouncing.current = false;
setPosition(0);
}, 350);
return;
}
}
它按预期工作!
问题
我有什么理由不应该这样做(从
setTimeout
)?
您可以从 setTimeout
呼叫 setState
。例如,这是实现动画的方法之一。
但在您的情况下,您应该将代码移至 useEffect
挂钩,否则可能会导致副作用。
并且您还需要清除卸载超时
useEffect(() => {
return () => {
if (bounceTimeout.current !== null) {
clearTimeout(bounceTimeout.current)
}
}
}, [])