首页 > 解决方案 > 反应导航问题

问题描述

我正在使用 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>
        );
    }
}

标签: react-nativereact-navigation

解决方案


我认为您的问题不在于导航,因为您没有清除 watchID 尝试添加以下内容

componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchId);
  }  

推荐阅读