我正在使用react-navigation 3,并且有2个主屏幕和地图屏幕,在地图屏幕中,我正在获取用户当前位置,如下所示:
componentWillMount() {
this.getCurrrentLcation()
}
getCurrrentLcation (){
this.watchID = navigator.geolocation.watchPosition(
position => {
const { coordinate, routeCoordinates, distanceTravelled } = this.state;
const { latitude, longitude } = position.coords;
const newCoordinate = {
latitude,
longitude
};
this.setState({
latitude,
longitude,
routeCoordinates: routeCoordinates.concat([newCoordinate]),
distanceTravelled:
distanceTravelled + this.calcDistance(newCoordinate),
prevLatLng: newCoordinate
});
},
error => console.log(error),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
}
当我第一次导航到地图屏幕时,调用了getCurrentLocation函数,它工作正常,但是当我按返回按钮并再次导航到地图屏幕时,它不显示当前位置,我认为getCurrentLocation没有被调用。
App.js
const RootStack = createStackNavigator(
{
Home: HomeScreen,
Maps: Maps,
},
{
initialRouteName: 'Home',
}
);
const Container= createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <Container/>;
}
}
HomeScreen.js
class HomeScreen extends Component {
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={()=>this.props.navigation.push('Maps')}>
<Text>Go to Maps</Text>
</TouchableOpacity>
</View>
);
}
}
答案 0 :(得分:0)
尝试使用 withNavigationFocus API https://reactnavigation.org/docs/en/with-navigation-focus.html
并将此生命周期添加到您的类组件中
...
componentDidUpdate(prevProps) {
if (this.props.isFocused && !prevProps.isFocused) {
// call your location function
this.getCurrrentLcation()
}
}
...
答案 1 :(得分:0)
我认为您的问题不在于导航,这是因为您没有清除watchID并尝试添加以下内容
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchId);
}