在下面的代码中,当应用程序最初加载“位置变化离线!”每次位置更新时都会记录。当online设置为TouchableOpacity时,记录到控制台的消息如下所示:
LOG true
LOG attempting to update location...
LOG Location updated in real-time!
LOG false
LOG Location changed offline!
LOG true
LOG attempting to update location...
LOG true
LOG attempting to update location...
LOG Location updated in real-time!由于某些原因,它正在随机地将online状态更改为false,从而导致“位置离线更改!”被记录下来。是什么导致了这一切?
const [online, setOnline] = useState(false);
useEffect(() => {
Geolocation.watchPosition(
position => {
console.log(online);
if (online) {
console.log('attempting to update location...');
const payload = {
lat: position.coords.latitude,
lng: position.coords.longitude,
id: 1,
};
axios
.post('http://localhost:3000/location/update', payload)
.then(res => {
if (res.status === 200) {
console.log('Location updated in real-time!');
return;
}
})
.catch(err => console.log(err.response));
} else {
console.log('Location changed offline!');
}
},
err => console.log(err.response)
);
}, [online]);发布于 2022-09-01 01:32:01
这里的问题是,每次online更改时都会添加一个新的观察者来永远捕获当前值。
在效果钩子中添加订阅(如Geolocation.watchPosition())应始终在清除函数中删除。
useEffect(() => {
const watchId = Geolocation.watchPosition(async (position) => {
console.log("online?", online);
if (online) {
console.log("attempting to update location...");
const payload = {
lat: position.coords.latitude,
lng: position.coords.longitude,
id: 1,
};
try {
await axios.post("http://localhost:3000/location/update", payload);
// no need to check the response status
console.log("Location updated in real-time!");
} catch (err) {
console.warn(err.toJSON()); // Axios helper, much nicer to look at
}
} else {
console.log("Location changed offline!");
}
}, console.error);
// return a cleanup function
return () => {
Geolocation.clearWatch(watchId);
};
}, [online]);https://stackoverflow.com/questions/73563408
复制相似问题