我内部有一个Mapview
组件和一个Marker
组件,如下所示:
import React, {useContext, useState, useEffect} from 'react';
import {StyleSheet} from 'react-native';
import MapView, {PROVIDER_GOOGLE, Marker} from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
import Toast from 'react-native-root-toast';
import {ThemeContext} from '~/utils/theme-context';
import {MAP_STYLE} from '~/utils/map.style';
import {Colors} from '~/styles';
const LATITUDE_DELTA = 0.01;
const LONGITUDE_DELTA = 0.01;
const Map = props => {
const themeContext = useContext(ThemeContext);
const mapStyle = MAP_STYLE;
let map = null;
let initialRegion = {
latitude: 35.78825,
longitude: -120.4324,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
};
const [region, setRegion] = useState(initialRegion);
const getCurrentPosition = Geolocation.getCurrentPosition;
const mapAnimation = map?.current.animateToRegion;
useEffect(() => {
const animate = location => {
if (map) {
mapAnimation(location, 1000);
}
};
const getPositionHandler = () => {
return getCurrentPosition(
info => {
const location = {
latitude: info.coords.latitude,
longitude: info.coords.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
};
animate(location);
setRegion(location);
},
error => {
Toast.show(error.message, {
backgroundColor: Colors.ERROR,
textColor: Colors.WHITE,
});
},
);
};
getPositionHandler();
}, [getCurrentPosition, mapAnimation, map]);
return (
<MapView
ref={map}
provider={PROVIDER_GOOGLE}
style={styles.map}
customMapStyle={themeContext.theme === 'light' ? [] : mapStyle}
region={region}>
<Marker
coordinate={{latitude: region.latitude, longitude: region.longitude}}
/>
</MapView>
);
};
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,
borderRadius: 24,
},
});
export default Map;
即使它并没有妨碍我进一步编码,我似乎仍然陷在这个问题中,但是该错误涉及内存泄漏等问题,这引起了我的关注。请帮忙
答案 0 :(得分:0)
我认为您的map
裁判可能是这里的问题。它会在每个渲染器上初始化,并设置为新渲染的地图的ref。虽然,如果地图动画正确,那么我不确定。
尝试改用useRef
,然后查看警告是否消失。
const map = useRef(null)
const mapAnimation = map.current?.animateToRegion;