[英]while loop is not working in useEffect hook
I want to get device location in every 7 seconds set set the state with current location values.我想每 7 秒获取一次设备位置,将状态设置为当前位置值。 I am making a while loop in useEffect hook and use setTimeot to wait 7 seconds.
我正在 useEffect 钩子中创建一个 while 循环并使用 setTimeot 等待 7 秒。 But while loop never executes.
但是 while 循环永远不会执行。 What is wrong with this approach and how can i solve the problem?
这种方法有什么问题,我该如何解决问题?
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: latitude, lon: longitude, alt: altitude, acc: accuracy })
alert("latitude: " + latitude + "\nlongitude: " + longitude)
setLoading(false)
})
.catch(err => alert(err))
sleep(7000)
}
}
useEffect(() => {
getPosition()
}, [])
I'm not 100% sur why the whuile(true)
doesn't work ... But why don't you use the "setTimeout's brother" setInterval
:我不是 100% sur 为什么
whuile(true)
不起作用......但你为什么不使用“setTimeout的兄弟” setInterval
:
const getPosition = () => {
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000,
})
.then((location) => {
const { latitude, longitude, altitude, accuracy } = location;
setPosition({
lat: latitude,
lon: longitude,
alt: altitude,
acc: accuracy,
});
alert('latitude: ' + latitude + '\nlongitude: ' + longitude);
setLoading(false);
})
.catch((err) => alert(err));
};
useEffect(() => {
const intervalID = setInterval(getPosition, 7*1000);
// Don't forget to clear the interval when unmounting the component :
return () => {
clearInterval(intervalID);
};
}, []);
Here is how it would be done using setTimeout
.这是使用
setTimeout
完成的方法。
The following article explains some subtleties of choosing one over the other.下面的文章解释了选择一个而不是另一个的一些微妙之处。
TLDR setTimeout
is usually a better choice TLDR
setTimeout
通常是更好的选择
Repeated Events: Timeout or Interval? 重复事件:超时还是间隔?
const loopInterval = 7*1000;
let loop;
const getPosition = () => {
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000,
})
.then((location) => {
const { latitude, longitude, altitude, accuracy } = location;
setPosition({
lat: latitude,
lon: longitude,
alt: altitude,
acc: accuracy,
});
alert('latitude: ' + latitude + '\nlongitude: ' + longitude);
setLoading(false);
loop = setTimeout(getPosition, loopInterval);
})
.catch((err) => alert(err));
};
useEffect(() => {
loop = setTimeout(getPosition, loopInterval);
// Clear the timeout when unmounting the component :
return () => {
clearTimeout(loop);
};
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.