我想在每7秒內獲得設備的位置,用當前的位置值設定狀態。我在useEffect鉤子中做了一個while回圈,并使用setTimeot來等待7秒。但while回圈從未執行過。這種方法有什么問題,我怎樣才能解決這個問題?
const sleep = (milliseconds) => {
setTimeout(() => { }, milliseconds)
}
const getPosition = () => {
while (true) {
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000,
})
.then(location => {
const { latitude, longitude, altitude, accuracy } = location
setPosition({ lat: 緯度, lon: 經度, alt: 高度, acc: 精度 })
alert("緯度。" 緯度 "
經度。" 經度)
setLoading(false)
})
.catch(err => alert(err))
sleep(7000)
}
}
useEffect(() => {
getPosition()
}, [])
uj5u.com熱心網友回復:
我不是百分之百的清楚為什么whuile(true)不能作業 ...
但你為什么不使用 "setTimeout的兄弟" setInterval :
const getPosition = () => {
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000,
})
.then((location) => {
const { latitude, longitude, altitude, accuracy } = location;
setPosition({
lat: 緯度。
lon: 經度,
alt: 海拔高度。
acc: 精度。
});
alert('latitude: ' latitude ')
經度:' 經度)。
setLoading(false)。
})
.catch((err) => alert(err))。
};
useEffect(() => {
const intervalID = setInterval(getPosition, 7*1000);
// 在卸載組件時不要忘記清除間隔時間。
return() => {
clearInterval(intervalID)。
};
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/326326.html
標籤:
下一篇:安裝NPM導航依賴包時出錯
