如何解决React Native useState 在 watchPositionAsync 中不起作用
我正在尝试使用 React-Native-Maps 折线。但是,当用户四处移动时,将新坐标添加到数组时,我无法弄清楚我做错了什么。我的代码如下:
const Walk = () => {
const [location,setLocation] = useState();
const [coords,setCoords] = useState();
const [last,setLast] = useState();
const [watch,setWatch] = useState();
const { onWalk,distance,setDistance,isPaused } = useContext(WalkContext);
const getInitLocation = async () => {
const { granted } = await Location.requestPermissionsAsync();
if (!granted) return;
const currentLocation = await Location.getCurrentPositionAsync({});
setLocation(currentLocation.coords);
const firstLast = {
latitude: currentLocation.coords.latitude,longitude: currentLocation.coords.longitude
};
setLast(firstLast);
setCoords([firstLast]);
}
const watchPosition = async () => {
let newLoc;
setWatch(
newLoc = await Location.watchPositionAsync({
accuracy: Location.Accuracy.High,timeInterval: 1000000,distanceInterval: 100
},position => {
const { latitude,longitude } = position.coords;
const newCoord = {
latitude,longitude
}
if (last) {
const newDist = distanceBetween(
last.latitude,last.longitude,newCoord.latitude,newCoord.longitude
);
setDistance(distance + newDist);
setLast(newCoord);
}
const newCoords = [...coords,newCoord];
setCoords(newCoords);
setLocation(position.coords);
},err => console.log(err))
);
}
const stopWatching = () => {
if (watch) {
watch.remove();
}
}
useEffect(() => {
if (!location) {
getInitLocation();
}
if (isPaused) {
watchPosition();
} else {
stopWatching();
}
},[isPaused]);
}
地图效果很好,只是我正在努力将新坐标正确添加到坐标状态。似乎它只将初始和最后一个坐标添加到数组中。任何帮助表示赞赏。我确定这是一个简单的错误,但我无法弄清楚。
解决方法
嘿,您使用 setWatch() 不正确,它只接受需要返回数据的数据或函数 我可以看到你没有在 useWatch() 中返回任何东西
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。