Реагировать на проблему с навигацией - PullRequest
0 голосов
/ 30 ноября 2018

Я использую реагирующую навигацию 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>
        );
    }
}

Ответы [ 2 ]

0 голосов
/ 30 ноября 2018

Я думаю, что ваша проблема не в навигации, а в том, что вы не очищаете watchID, попробуйте добавить следующее

componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchId);
  }  
0 голосов
/ 30 ноября 2018

Попробуйте использовать с API NavigationFocus , https://reactnavigation.org/docs/en/with-navigation-focus.html

и добавить этот жизненный цикл в компонент класса

...
componentDidUpdate(prevProps) {
    if (this.props.isFocused && !prevProps.isFocused) {
        // call your location function
        this.getCurrrentLcation()
    }
}
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...