react-native - 反应导航问题
问题描述
我正在使用 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 不是被调用。
应用程序.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>
);
}
}
解决方案
我认为您的问题不在于导航,因为您没有清除 watchID 尝试添加以下内容
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchId);
}
推荐阅读
- java - Java FX 8 在 Application init() 方法中使用 Platform.runLater() 来显示警报/登录框
- c# - 有没有办法在方法输入参数上添加数据注释?
- python - 在 python 中将变量值传递给 SQL 时出现多个 aguements 错误
- javascript - JSPDF 打印不正确,显示空白 pdf
- python - 在关闭文件的 Python 3 I/O 操作中附加文件
- java - 没有使用 Spring Boot + OAuth2 + Gitlab 身份验证重定向到应用程序
- sql - varchar T-sql 中每个字符的数据类型
- erp - 嵌入式 SQL - Baan/LN 编程
- jmeter - JMeter 线程组 - 创建 UI 并使流程自动化
- python-3.x - 如何更改字典值中的删除重复元素,python3?