gpt4 book ai didi

reactjs - react 如何在 useEffect 之外清除 setTimeout

转载 作者:行者123 更新时间:2023-12-04 00:56:16 26 4
gpt4 key购买 nike

如果我像这样在 useEffect 之外使用 setTimeout 和 setState ,我该如何在卸载时清理它?

const MyComponents = () => {
const [myState, setMyState] = useState(null);

const handlePress = () => {
setTimeout(() => {
setMyState('...');
}, 1000);
};

return <button onPress={handlePress} />;
};

如果我在时间到之前离开页面(例如组件卸载),我会得到
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

最佳答案

将超时 id 保存在引用中并在清理效果中使用它:

const MyComponents = () => {
const [myState, setMyState] = useState(null);

const idRef = useRef();

useEffect(() => {
const timeoutId = idRef.current;
return () => {
clearTimeout(timeoutId);
};
}, []);

const handlePress = () => {
const id = setTimeout(() => {
setMyState("...");
}, 1000);
idRef.current = id;
};

return <button onPress={handlePress} />;
};

关于reactjs - react 如何在 useEffect 之外清除 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62318281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com