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);
'てみましょう自己=この; navigator.geolocation.getCurrentPosition(関数(位置){ self.setState({ LAT:1 }); }、 (エラー)=>アラート(error.message) ); ' - これは私の作品。 – Phil
@Philそれはありがとうございます!私はあなたがES6でこれを行う必要はなかったが、私はこのテクニックを使用して例を見つけることができませんでしたか?いずれにしても感謝! –
聞いてよかった!うん...時々あなたは 'this'でvar/letを設定しなければなりません。たとえば、 'forEach'を使い、この' forEach'の外にあるスコープにアクセスしたいときなどです。 – Phil