我正在构建一个旅行应用程序。该应用程序中的屏幕之一是地图屏幕。我使用Expo Locations中的watchPositionAsync。 watchPositionAsync可以很好地运行并传递用户坐标。我希望watchPositionAsync在“地图”屏幕/模块关闭后停止/删除。我将.remove()函数附加到watchPositionAsync,但是不幸的是watchPositionAsync继续运行。模态关闭后,如何使其停止运行?
我尝试以各种不同方式使用.remove(): -componentWillUnmount等。 -我什至尝试在按钮(onPress)中执行它
async componentWillMount() {
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status === 'granted') {
this._getLocationAsync();
} else {
this.setState({ error: 'Locations services needed' });
}
}
componentWillUnmount() {
this._stopGetLocationAsync().catch(err => console.log('err'));
}
_getLocationAsync = async () => {
const location = await Location.watchPositionAsync(
{
enableHighAccuracy: true,
distanceInterval: 1,
timeInterval: 10000
},
newLocation => {
let coords = newLocation.coords;
// this.props.getMyLocation sets my reducer state my_location
this.props.getMyLocation({
latitude: parseFloat(coords.latitude),
longitude: parseFloat(coords.longitude)
});
},
error => console.log(error)
);
return location;
};
_stopGetLocationAsync = async () => {
const location = await Location.watchPositionAsync();
return location.remove();
};
我期望在卸载组件后将watchPositionAsync删除,但是当我console.log(location.remove())时,我变得不确定。
答案 0 :(得分:0)
在您的_stopGetLocationAsync
中,您将创建一个新的watchPositionAsync
承诺对象并将其删除。因此,_getPositionASync
中的原始地址仍然存在。
您需要将const Location更改为类变量i.e. this.location=...
,然后将remove方法传递给该变量。
这是修改后的代码
async componentWillMount() {
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status === 'granted') {
this._getLocationAsync();
} else {
this.setState({ error: 'Locations services needed' });
}
}
componentWillUnmount() {
this.location.remove(callback...);
}
_getLocationAsync = async () => {
this.location = await Location.watchPositionAsync(
{
enableHighAccuracy: true,
distanceInterval: 1,
timeInterval: 10000
},
newLocation => {
let coords = newLocation.coords;
// this.props.getMyLocation sets my reducer state my_location
this.props.getMyLocation({
latitude: parseFloat(coords.latitude),
longitude: parseFloat(coords.longitude)
});
},
error => console.log(error)
);
return location;
};