关于如何在类组件中使用react-native-maps有很多示例,但是我还没有找到那些带有无状态组件的示例。我使用无状态组件访问全局状态。在获得用户的位置后,我需要从初始区域中移动MapView的摄像机视图,在互联网上搜索后,我最终以某种方式结束了这段代码不起作用。
import React, { useState, useEffect, useRef } from 'react'
import MapView, { Marker, PROVIDER_GOOGLE } from 'react-native-maps';
...
const Explore = props => {
const [userCoords, setUserCoords] = useState({
latitude: 0,
longitude: 0
})
const mapRef = useRef(null);
onMapReady = () => {
getUserLocation()
}
getUserLocation = async () => {
Geolocation.getCurrentPosition(
async (position) => {
setUserCoords(position.coords)
mapRef.animateToRegion({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
})
},
async (error) => {
// See error code charts below.
console.log("Geolocation Error" + error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000 }
);
}
return(
...
<MapView
ref={mapRef}
onMapReady={() => onMapReady()}
region={{
latitude: userCoords.latitude,
longitude: userCoords.latitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
showsUserLocation={true}>
...
</MapView>
)
...
export default Explore
请帮助我〜谢谢
答案 0 :(得分:1)
您需要使用mapRef.animateToRegion
来代替mapRef.current.animateToRegion
答案 1 :(得分:0)
基于React Documents的引用在无状态组件下不可用,您需要将类扩展与react组件一起使用, 如果您要访问全局状态,我强烈建议您使用Redux来实现此目的, 现在开始学习redux,并不需要花费一天多的时间。