我有一个MapView,我试图专注于用户的当前位置。现在,我正在记录位置,并记录当前区域。我的问题是组件正在显示日志中的空数组,并且在循环循环后,将状态设置为位置坐标,以便MapView向我展示了海洋中间的某个地方。为什么初始区不抓住变化的状态和渲染?
const screen = Dimensions.get('window');
const ASPECT_RATIO = screen.width / screen.height;
var LATITUDE_DELTA = 0.3022;
var LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
class MapScreen extends Component {
constructor(props) {
super(props)
this.state = {
currentRegion: []
}
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position)
this.setState({ currentRegion: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA
}})
},
(error) => alert(error.message),
{timeout: 20000, maximumAge: 1000}
)
}
render () {
console.log(this.state.currentRegion)
return(
<View style={styles.container}>
<MapView
showsUserLocation = {true}
style={styles.map}
initialRegion={this.state.currentRegion}
/>
</View>
)
}
}
在大量搜索之后,我终于得到了解决方案。每次都对我有用。
只需将"初始区"替换为"区域"。
启动区域在安装后更改该区域时不会更新区域。根据定义,它仅仅是初始起点。
MapView Props中的文档中提到了这一点: https://github.com/airbnb/react-native-maps/blob/master/master/docs/mapview.md
由于MapView在您的状态更新之前正在安装,因此它使用空数组。尝试使用ComponentWillMount()而不是ComponentDidMount(),以使您的状态更改更快。如果那不起作用,您也可以尝试设置构造函数中的当前位置。
初始区域应为对象。您已经将其保存为您的州阵列。
constructor(props){
super(props);
this.state = {
currentRegion: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}
}
}