【发布时间】:2016-07-11 08:33:10
【问题描述】:
我是 react-native 的新手,我正在尝试使用地理位置来更新状态。
在 componentDidMount() 中,我可以调用 this.setState({lat: 1}); 并且它可以工作。但是,如果我从 geolocation.getCurrentPosition() 回调中调用this.setState({lat: 1});,应用程序就会崩溃。我正在物理设备上进行测试。
我已剥离一切以隔离问题。非常感谢任何帮助。
这是我的代码:
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);
【问题讨论】:
-
let self = this; navigator.geolocation.getCurrentPosition(function(position) { self.setState({ lat: 1 }); }, (error) => alert(error.message) );- 这对我有用。 -
@Phil 它的工作原理谢谢!我虽然你不必用 ES6 来做这件事,但我找不到任何使用这种技术的例子?不管怎样,谢谢!
-
很高兴听到!是的...有时您必须使用
this设置一个var/let。例如,当您使用forEach并希望访问此forEach之外的范围时。
标签: javascript android geolocation react-native state