所以,我正在使用expo和react-navigation来创建一个android应用程序。我想每 1 秒调用一个函数,但也想根据响应清除间隔。代码如下:
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
);
};
我不知道为什么clearInterval在这里不起作用或者我是否做错了什么。
最佳答案
这很可能是由于 res.someThing
是“错误的”。如果看不到响应,调试将变得困难。
您似乎正在尝试实现某种轮询。更好的方法是使用清理函数清除间隔。示例:
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
}
此函数通过清除设置获取函数的值时的间隔来完成您想要的操作。如果该值是您想要的值,它将清除间隔并仅设置另一个间隔。
关于javascript - 无法清除 Expo React native 应用程序中的间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62892039/