【发布时间】:2020-08-09 13:10:34
【问题描述】:
我有一个屏幕组件,它有一个 getPosition() 函数,每隔一段时间就会调用一次。
如果调用了stopRace() 函数,或者如果用户按下物理/图形后退按钮,我想清除此间隔,使其不会继续在后台运行。
为此,我尝试将间隔 ID 存储在 raceUpdateInterval 状态变量中。
然后我在stopRace() 函数和cleanup() 函数中使用clearInterval(raceUpdateInterval) 清除此间隔。
当我调用stopRace() 函数,然后按回,间隔被清除。我知道这一点是因为我的控制台日志:
Still Running
Still Running
Still Running
Reached cleanup function
但是,如果我按下后退按钮,间隔不会清除。相反,我的控制台日志:
Still Running
Still Running
Still Running
Reached cleanup function
Still Running
随后是包含以下建议的内存泄漏警告:
To fix, cancel all subscriptions and asynchronous tasks in %s.%s, a useEffect cleanup function
这正是我想要做的,但由于某种超出我理解的原因无法正常工作。
这里是组件的相关代码:
const RaceScreen = ({route, navigation}) => {
const [raceUpdateInterval, setRaceUpdateInterval] = useState(0);
useEffect(function() {
return function cleanup() {
console.log('Reached cleanup function')
clearInterval(raceUpdateInterval)
}
}, []);
function getPosition(){
console.log("Still being called")
//get position
}
function startRace(){
setRaceUpdateInterval(setInterval(getPosition, 1000))
}
function stopRace(){
clearInterval(raceUpdateInterval)
}
为什么stopRace() 函数能正确清除区间而cleanup() 函数不能?
【问题讨论】:
标签: javascript react-native react-hooks