【问题标题】:React Navigation Issue反应导航问题
【发布时间】:2018-11-30 17:46:26
【问题描述】:

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

【问题讨论】:

    标签: react-native react-navigation


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      尝试使用 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()
          }
      }
      ...
      

      【讨论】:

      • 我认为问题出在地图上,因为我尝试在 getCurrentLocation 函数中发出警报,并且警报工作正常,只是 setState lat, long 不起作用
      猜你喜欢
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多