2017-03-03 80 views
0

我有一個MapView,我試圖專注於用戶的當前位置。現在我正在記錄位置,並記錄currentRegion狀態。我的問題是組件顯示日誌中的空數組,並且在它通過渲染循環之後,它將狀態設置爲位置座標,以便MapView顯示我在海洋中間的某處。爲什麼initialRegion沒有抓住變化的狀態和渲染?React本地問題與狀態和MapView組件中的initialRegion

const screen = Dimensions.get('window'); 
    const ASPECT_RATIO = screen.width/screen.height; 

    var LATITUDE_DELTA = 0.3022; 
    var LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; 

    class MapScreen extends Component { 
     constructor(props) { 
     super(props) 
     this.state = { 
      currentRegion: [] 
     } 
     } 

     componentDidMount() { 
     navigator.geolocation.getCurrentPosition(
      (position) => { 
      console.log(position) 
      this.setState({ currentRegion: { 
       latitude: position.coords.latitude, 
       longitude: position.coords.longitude, 
       latitudeDelta: LATITUDE_DELTA, 
       longitudeDelta: LONGITUDE_DELTA 
      }}) 
      }, 
      (error) => alert(error.message), 
      {timeout: 20000, maximumAge: 1000} 
     ) 
     } 

     render() { 
     console.log(this.state.currentRegion) 
     return(

      <View style={styles.container}> 
      <MapView 
       showsUserLocation = {true} 
       style={styles.map} 
       initialRegion={this.state.currentRegion} 
      /> 
      </View> 
     ) 
     } 
    } 

回答

0

initialRegion prop在安裝完成後更改其prop後,不更新該區域。根據定義,它僅僅是最初的起點。
這是在文檔下MapView的道具提到: https://github.com/airbnb/react-native-maps/blob/master/docs/mapview.md

因爲MapView的是安裝你的狀態更新之前,它使用空數組。嘗試使用ComponentWillMount()而不是ComponentDidMount(),以便更快地進行狀態更改。如果這不起作用,你也可以嘗試在構造函數中設置當前位置。

0

initialRegion狀態應該是一個對象。你已經將它作爲一個數組保存在你的狀態中。

constructor(props){ 
    super(props); 
    this.state = { 
     currentRegion: { 
      latitude: LATITUDE, 
      longitude: LONGITUDE, 
      latitudeDelta: LATITUDE_DELTA, 
      longitudeDelta: LONGITUDE_DELTA, 
     } 
    } 
}