簡體   English   中英

在React Native中從componentDidMount獲取狀態失敗

[英]Get state from componentDidMount fails in React Native

我正在嘗試從componentDidMount(或渲染)函數獲取區域狀態,但是失敗。 你知道為什么嗎?

這是我的代碼:

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}

navigator.geolocation.getCurrentPosition是一個異步函數。 異步函數完成和調用適當的成功或失敗回調所花費的時間是不確定的。 它不能保證在componentDidMount調用之前發生。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM