【问题标题】:UI does not update on state changeUI 不会在状态更改时更新
【发布时间】:2020-04-22 15:11:14
【问题描述】:

我正在使用 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 上。

界面代码

<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。

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

【问题讨论】:

  • findingLocation以外的地方打了多少次电话,在哪里打电话,componentDidMount除外
  • 只在componentDidMount中一次。

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


【解决方案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);
})

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    相关资源
    最近更新 更多