【发布时间】:2021-05-05 17:45:27
【问题描述】:
我正在尝试使用 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]);
}
地图效果很好,只是我正在努力将新坐标正确添加到坐标状态。似乎它只将初始坐标和最后一个坐标添加到数组中。任何帮助表示赞赏。我确定这是一个简单的错误,但我无法弄清楚。
【问题讨论】:
-
您是否在另一个 setState 函数中设置状态?
标签: reactjs react-native use-state react-native-maps