【发布时间】:2017-10-13 18:50:57
【问题描述】:
在调用 getCurrentPosition() 之后,我试图从 componentDidMount() 调用一个函数。如果我将位置传递给 updatePosition,则应用程序崩溃。如果我将 updatePosition 函数的内容移动到 getCurrentPosition() 中,那么它就可以工作。我需要做什么才能从 componentDidMount() 中调用成员函数。
class GeolocationViewer extends Component {
constructor(props) {
super(props);
this.state = {
lat: 0,
long: 0,
heading: 0,
accuracy: 0,
speed: 0,
pointCount: 0
};
}
updatePostion(position) {
var lat = position.coords.latitude;
this.setState({lat});
}
componentDidMount() {
let self = this;
setInterval(() => {
navigator.geolocation.getCurrentPosition((position) => {
// this breaks
this.updatePostion(position);
// if I place the body of updatePosition here it works.
},
(error) => {},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 10000}
);
}, 5000);
}
render() {
return (
<View style={{flex: 1, backgroundColor: 'black'}}>
<View style={{flex: 1, color: 'green'}}>
<Text style={styles.green}>
Position: {this.state.lat}, {this.state.long}
</Text>
<Text style={styles.green}>
Heading: {this.state.heading}
</Text>
<Text style={styles.green}>
Speed: {this.state.speed}
</Text>
<Text style={styles.green}>
Accuracy: {this.state.accuracy}
</Text>
<Text style={styles.green}>
Point Count: {this.state.pointCount}
</Text>
</View>
</View>
);
}
}
【问题讨论】:
标签: javascript reactjs react-native