【发布时间】:2021-06-03 14:43:44
【问题描述】:
我正在开发一个每隔 X 秒需要一个用户位置的应用。当组件被挂载时,间隔开始并获取 GPS 位置并将其与保存在组件状态中的旧位置进行比较。
问题是,间隔仅与变量的默认状态进行比较,因此如果新值与旧值不同,则会调用 setter 来更改该值。 我在位置 var 上使用了 useEffect,所以每当它发生变化时,只需打印它,它就会按新值正确执行。
但间隔继续使用 useState 挂钩中给出的默认值。
我在这里缺少什么。 我的代码示例如下:
const [currentLocation, setCurrentLocation] = useState(null);
let locationInterval = null;
useEffect(() => {
locationInterval = setInterval(async () => {
console.log("IN INTERVAL");
navigator.geolocation.getCurrentPosition((location, error) => {
if (location) {
location = [location.coords.latitude, location.coords.longitude];
/// currentLocation is not updating here for some reason
if (JSON.stringify(location) !== JSON.stringify(currentLocation)) {
alert(
`the new location in interval ${location} old location: ${currentLocation}`
);
setCurrentLocation(location);
}
} else {
console.log(error);
}
});
}, 15000);
}, [map]);
useEffect(() => {
return () => {
clearInterval(locationInterval);
};
}, []);
useEffect(() => {
/// currentLocation is updated here from the setInterval
console.log("newlocation", currentLocation);
}, [currentLocation]);
【问题讨论】:
-
您似乎错过了要分享的代码的前几行。 setInterval 是否也在 useEffect 中?
-
是的,修复了帖子。
-
我刚刚回答了你的问题,但另一方面,需要提到你的代码中还有其他问题......比如你清除间隔的方法不正确。
-
能不能去掉原生的alert方法,原生的alert会阻塞js的执行。改用控制台怎么样。
标签: reactjs react-hooks gps state intervals