2017-03-03 5 views
0

私はMapViewを持っており、ユーザーの現在地に焦点を当てようとしています。今私は、位置をログに記録し、currentRegion状態を記録しています。私の問題は、コンポーネントがログに空の配列を表示していることです。レンダリングを繰り返すと、状態が位置座標として設定されるため、MapViewは海の真ん中に私を見せてくれます。なぜinitialRegionは変更された状態とレンダリングを取得していないのですか?React MapViewコンポーネントのstateと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プロップは、プロップがマウントされた後に変更された場合、リージョンを更新しません。定義によると、それは単なる出発点に過ぎない。
これはMapViewの小道具の下でドキュメントに記載されている: https://github.com/airbnb/react-native-maps/blob/master/docs/mapview.md

のMapViewは、あなたの状態が更新される前に設置されているので、それは空の配列を使用しています。 ComponentDillMount()の代わりにComponentWillMount()を使用して、状態の変更がより早く行われるようにしてください。それでも機能しない場合は、コンストラクタの現在の位置を設定することもできます。

0

initialRegion状態はオブジェクトである必要があります。あなたはあなたの状態の配列としてそれを保持しています。

constructor(props){ 
    super(props); 
    this.state = { 
     currentRegion: { 
      latitude: LATITUDE, 
      longitude: LONGITUDE, 
      latitudeDelta: LATITUDE_DELTA, 
      longitudeDelta: LONGITUDE_DELTA, 
     } 
    } 
} 
関連する問題