gpt4 book ai didi

javascript - 如何从 componentDidMount 调用成员函数

转载 作者:行者123 更新时间:2023-12-03 06:31:22 25 4
gpt4 key购买 nike

我试图在调用 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>
);
}
}

最佳答案

事实上,这一切都有效!这是一个RNplay example及其代码:

'use strict';

var React = require('react');
var {
Component,
} = React;
var ReactNative = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = ReactNative;

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() {
setInterval(() => {
navigator.geolocation.getCurrentPosition((position) => {
this.updatePostion(position);
},
(error) => {},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 10000}
);
}, 5000);
}

render() {
console.log(this.state);
return (
<View style={{flex: 1, padding: 30}}>
<View style={{flex: 1}}>
<Text>
Position: {this.state.lat}, {this.state.long}
</Text>
<Text>
Heading: {this.state.heading}
</Text>
<Text>
Speed: {this.state.speed}
</Text>
<Text>
Accuracy: {this.state.accuracy}
</Text>
<Text>
Point Count: {this.state.pointCount}
</Text>
</View>
</View>
);
}
}

AppRegistry.registerComponent('SampleApp', () => GeolocationViewer);

(检查控制台日志)

关于javascript - 如何从 componentDidMount 调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38435460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com