【问题标题】:Get state from componentDidMount fails in React Native在 React Native 中从 componentDidMount 获取状态失败
【发布时间】:2016-06-05 19:12:38
【问题描述】:

我正在尝试从 componentDidMount(或渲染)函数获取 region 状态,但它失败了。你知道为什么吗?

这是我的代码:

constructor(props) {

  super(props);

  navigator.geolocation.getCurrentPosition(
    (position) => {
      this.region = {
        latitude: position.coords.latitude,
        latitudeDelta: 0.005,
        longitude: position.coords.longitude,
        longitudeDelta: 0.005,
      }
      console.log("location from constructor:", this.region);
    },
    (error) => alert(error.message),
    {enableHighAccuracy: true, timeout: 20000, maximumAge: 2000}
  );

  this.state = {
    region: this.region
  }

}

componentDidMount() {

  console.log("location from componentDidMount:", this.state.region);

}

这是我的日志:

location from componentDidMount: undefined

location from constructor: Object {latitude: 48.8732, latitudeDelta: 0.005, longitude: 2.402855, longitudeDelta: 0.005}

【问题讨论】:

    标签: javascript react-native ecmascript-6 react-jsx


    【解决方案1】:

    navigator.geolocation.getCurrentPosition 是一个异步函数。异步函数完成和调用适当的成功或失败回调所用的时间是不确定的。不保证在 componentDidMount 调用之前发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-20
      • 2021-07-09
      • 2017-02-18
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 2019-11-27
      • 2017-09-05
      相关资源
      最近更新 更多