[英]Stop infinite loop in react native useEffect
I am calling one function through setInterval
but function go to infinite loop and my applicaiton get stuck.我通过
setInterval
调用一个 function 但 function go 无限循环,我的应用程序卡住了。 It's happen it on android, Could someone please help me how to resolve this issue.它发生在 android,有人可以帮我解决这个问题。
Thanks谢谢
useEffect(() => {
const interval = setInterval(() => {
sendCoordinate(location);
}, 180000);
return () => clearInterval(interval);
}, [location]);
A function that I am calling我正在呼叫的 function
const sendCoordinate = async (locParms) => {
console.log("@2 it working3", checkDayStatus, location);
if (checkDayStatus === "Started") {
let data = {
lat:
locParms !== null
? locParms && locParms.lat
: location && location.lat,
lng:
locParms !== null
? locParms && locParms.lng
: location && location.lng,
dispatcher_id: 1,
truck_id: 1,
};
return await LocationAPI.sendLocationFeed(data);
}
};
It turns out that your timer is created every time, just leave the useEffect arguments empty, [location] -> []原来你的timer每次都是创建的,把useEffect arguments留空就行了,[location] -> []
useEffect(() => {
const interval = setInterval(() => {
sendCoordinate(location);
}, 180000);
return () => clearInterval(interval);
}, [location.lng, location.lat]);
So you need to change the location from the dependency array like this.所以你需要像这样从依赖数组中更改位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.