UI 不会随着状态变化而更新

2024-01-29

我正在使用反应本机地图和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();
}

}

And in 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 code

<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 https://github.com/react-native-community/react-native-maps对于地图和https://www.npmjs.com/package/@react-native-community/geolocation https://www.npmjs.com/package/@react-native-community/geolocation用于地理位置。

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


在 setState 函数中使用展开运算符。至于为什么,请看这篇文章:https://medium.com/pro-react/a-brief-talk-about-immutability-and-react-s-helpers-70919ab8ae7c 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);
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

UI 不会随着状态变化而更新 的相关文章

随机推荐