用户界面不会根据状态更改进行更新

时间:2020-04-22 15:11:14

标签: javascript reactjs react-native react-native-android react-native-maps

我正在使用React本机地图,并在componentDidMount()上要求用户启用其位置。

componentDidMount() {
if (Platform.OS === 'android') {
  RNAndroidLocationEnabler.promptForEnableLocationIfNeeded({ interval: 20000, fastInterval: 5000 })
    .then(data => {
      console.log(data);

      this.findingLocation();
    }).catch(err => {
    });
}
else if (Platform.OS === 'ios') {
  this.findingLocation();
}

}

findingLocation()中,我试图像这样获取用户的当前位置

 findingLocation = () => {
Geolocation.getCurrentPosition(
  position => {
    this.setState({
      region: {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        latitudeDelta: 0.0043,
        longitudeDelta: 0.0034,
      }
    }, () => {
      console.warn(this.state.region);
    });
  },
  error => console.warn('Error', JSON.stringify(error)),
  { enableHighAccuracy: true, timeout: 20000, maximumAge: 10000 },
);

}

在控制台中,我正在等待当前位置。 但这有时并不反映在UI上。

UI代码

<MapView
      provider={PROVIDER_GOOGLE}
      style={styles.map}
      region={this.state.region}
      onRegionChangeComplete={this.onRegionChange}
      zoomEnabled={true}
      showsUserLocation={true}
      zoomControlEnabled={true}
      showsMyLocationButton={true}
    />

我正在使用的图书馆是https://github.com/react-native-community/react-native-maps(用于MAP)和https://www.npmjs.com/package/@react-native-community/geolocation(用于GEOLOCATION)。

请帮帮我。 我要去哪里错了。 提前致谢。

1 个答案:

答案 0 :(得分:1)

在setState函数中使用传播运算符。至于原因,请阅读这篇文章:https://medium.com/pro-react/a-brief-talk-about-immutability-and-react-s-helpers-70919ab8ae7c

this.setState(prevState => ({
  region: {
    ...prevState.region
    latitude: position.coords.latitude,
    longitude: position.coords.longitude,
    latitudeDelta: 0.0043,
    longitudeDelta: 0.0034,
  }
}), () => {
  console.warn(this.state.region);
})