如果我在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.
答案 0 :(得分:3)
将超时ID保存在引用中,并用于清除效果:
const MyComponents = () => {
const [myState, setMyState] = useState(null);
const idRef = useRef();
useEffect(() => {
return () => {
clearTimeout(idRef.current)
};
}, []);
const handlePress = () => {
const id = setTimeout(() => {
setMyState("...");
}, 1000);
idRef.current = id;
};
return <button onPress={handlePress} />;
};