我目前正在尝试使用一个屏幕制作一个应用程序,其中屏幕的背景由以用户当前坐标为中心的地图占据。在下面的代码中,我在 App 类组件的状态中将经度和经度保存为 null。然后,我使用继承的方法“componentDidMount()”更新用户当前位置的状态,最后在 render() 中我使用 this.state.latitude 和 this.state.longitude 来通知纬度和经度的值地图视图。
代码无法编译。使用console.log,我将问题隔离为render() 被调用两次,我的console.log 语句首先将空值输出到控制台,然后输出用户的当前位置。
所以两个问题。
1)为什么console.log会向控制台输出两次不同的值,一次是传入的状态值,一次是componentDidMount()更新的状态值?
2) 如何运行函数 navigator.geolocation.getCurrentPosition() 来保存用户的当前位置并将其传递给 MapView 以便代码首先编译?
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { latitude: null, longitude: null };
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(position => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
});
});
}
render() {
return (
<View style={styles.container}>
<MapView
style={styles2.map}
initialRegion={{
latitude: this.state.latitude,
longitude: this.state.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
/>
{console.log(this.state.latitude)}
{console.log(this.state.longitude)}
</View>
);
}
}