繁体   English   中英

while 循环在 useEffect 钩子中不起作用

[英]while loop is not working in useEffect hook

我想每 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: latitude, lon: longitude, alt: altitude, acc: accuracy })
                    alert("latitude: " + latitude + "\nlongitude: " + longitude)
                    setLoading(false)
                })
                .catch(err => alert(err))
            sleep(7000)
        }
          
}


useEffect(() => {
    getPosition()

}, [])

我不是 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);
  };
}, []);

这是使用setTimeout完成的方法。

下面的文章解释了选择一个而不是另一个的一些微妙之处。

TLDR setTimeout通常是更好的选择

重复事件:超时还是间隔?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM