简体   繁体   English

无法在 Expo React 本机应用程序中清除间隔

[英]Unable to clear interval in Expo React native application

So, I am using expo and react-navigation to create an android application.所以,我正在使用 expo 和 react-navigation 创建一个 android 应用程序。 I want to call a function every 1 second but also want to clear the interval according to the response.我想每 1 秒调用一次 function 但也想根据响应清除间隔。 The code is as follows:代码如下:

import React,{useEffect,useState} from 'react';
const Home = props => {
    
    const [intervalId,setIntervalId]=useState(null);

    useEffect(()=>{
        let interval = setInterval(fetchData,1000);
        setIntervalId(interval);
    },[]);

    const fetchData = async () => {
        const response = await fetch(''); //fetch data from some URL here
        const res = await response.json();
        
        if(res.someThing) {
            clearInterval(intervalId); //clear interval using id stored in state
                                       //no errors but does not seem to clear the interval
        }
    };

    return (
        //JSX
    );

};

I don't know why clearInterval is not working here or if I am doing something wrong.我不知道为什么 clearInterval 在这里不起作用,或者我做错了什么。

Most likely this is due to res.someThing being "falsey".这很可能是由于res.someThing是“虚假的”。 Without seeing the response it will be hard to debug.如果没有看到响应,将很难调试。

It seems you are trying to achieve a kind of polling.看来您正在尝试实现一种轮询。 A better way of doing this would be to clear the interval using a clean up function.更好的方法是使用清理 function 来清除间隔。 Example:例子:

function Home() {
  const intervalId = useRef(0);
  const [value, setValue] = useState(null);

  useEffect(() => {
    // Clean the interval no matter what
    clearInterval(intervalId.current);

    // Conditionally set interval
    if (value === null) {
      intervalId.current = setInterval(fetchData, 1000);
    }

    // Clean up
    return () => clearInterval(intervalId.current);
  }, [value]);

  async function fetchData() {
    const response = await fetch("");
    const res = await response.json();
    setValue(res.someThing);
  }

  return null; // Render UI
}

This function does what you want, by clearing the interval when the value from the fetch function is set.这个 function 做你想做的事,通过清除设置来自 fetch function 的值的间隔。 It will clear the interval and only set another interval if the value is what you want it to be.它将清除间隔并仅在值是您想要的值时设置另一个间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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