简体   繁体   English

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

[英]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.

相关问题 带有 useSelector 的 useEffect 钩子的无限循环 - Infinite loop with useEffect hook with useSelector 为什么 PanResponder 不能使用 useEffect Hook? - Why PanResponder is not working with useEffect Hook? onSnapshot 在 useEffect 挂钩中无法正常工作 - onSnapshot is not working properly in useEffect hook useEffect 钩子循环运行并挂起应用程序 - useEffect hook is running in loop and hanging the application 异步 function 在 UseEffect Hook 中不工作 - Async function not working inside UseEffect Hook 带有依赖项数组的 React Native 动画 useEffect 钩子创建无限循环 - React Native animation useEffect hook with dependencies array creates infinite loop 在 useEffect 钩子中设置状态和 AsyncStorage 会导致无限循环? - Setting state along with AsyncStorage in useEffect hook causes infinite loop? usestate 挂钩与计时器在 useeffect 挂钩内无法正常工作 - usestate hooks combined with timers not working properly inside useeffect hook 在 React Native 中卸载组件期间,清理功能在 UseEffect Hook 中不起作用 - Cleaning Function not Working in UseEffect Hook During Component Unmount in React Native Promise 在 useEffect 挂钩中未解析 - Promise is not resolving in useEffect hook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM