状态改变时UI不更新

问题描述 投票:1回答:1

我使用的是 react native maps 和 on 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代码

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

我使用的图书馆是 https:/github.comreact-native-communityreact-native-maps。 for MAP & https:/www.npmjs.compackage@react-native-communitygeolocation。 为GEOLOCATION。

请帮帮我,我哪里做错了,先谢谢了。

javascript reactjs react-native react-native-android react-native-maps
1个回答
1
投票

在你的setState函数中使用传播操作符。至于为什么,请阅读这篇文章。https:/medium.compro-reacta-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);
})
© www.soinside.com 2019 - 2024. All rights reserved.