2016-07-11 12 views
0

私は反応ネイティブが新しく、ジオロケーションを使用して状態を更新しようとしています。ジオロケーションコールバックでcomponentDidMount()のsetStateが機能していません

componentDidMount()で私はthis.setState({lat: 1});を呼び出すことができ、動作します。しかし、私がthis.setState({lat: 1});をgeolocation.getCurrentPosition()コールバックから呼び出すと、アプリケーションがクラッシュします。私は物理的なデバイスでテストしています。

問題を特定するためにすべてを取り除きました。どんな助けでも大歓迎です。ここで

は私のコードです:私はちょうどself = thisを設定する必要がありました@Philに

import React, { Component } from 'react'; 
import { AppRegistry,ScrollView, ListView, Text, View } from 'react-native'; 

class TestProject extends Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
     lat: 0 
     }; 
    } 

    componentDidMount() { 
     navigator.geolocation.getCurrentPosition(function(position) { 
     this.setState({lat: 1}); // this causes a crash - without this line the app does not crash. 
     }, 
     (error) => alert(error.message) 
    ); 

    this.setState({lat: 1}); // this works 
    } 

    render() { 
    return (
     <View> 
     <Text> 
      {this.state.lat} 
     </Text> 
     </View> 
    ); 
    } 
} 

AppRegistry.registerComponent('TestProject',() => TestProject); 
+0

'てみましょう自己=この; navigator.geolocation.getCurrentPosition(関数(位置){ self.setState({ LAT:1 }); }、 (エラー)=>アラート(error.message) ); ' - これは私の作品。 – Phil

+0

@Philそれはありがとうございます!私はあなたがES6でこれを行う必要はなかったが、私はこのテクニックを使用して例を見つけることができませんでしたか?いずれにしても感謝! –

+0

聞いてよかった!うん...時々あなたは 'this'でvar/letを設定しなければなりません。たとえば、 'forEach'を使い、この' forEach'の外にあるスコープにアクセスしたいときなどです。 – Phil

答えて

-1

ありがとう:

let self = this; 
navigator.geolocation.getCurrentPosition(function(position) { self.setState({ lat: 1 }); }, (error) => alert(error.message)); 
関連する問題