【发布时间】:2021-01-11 23:52:22
【问题描述】:
参考:How do i update marker position without re rendering mapview ? React native maps
我的目标是防止在用户拖动地图同时更改市场坐标时重新渲染。目前的解决方案是使用useState钩子。但它会导致组件重新渲染,从而导致应用程序卡顿。
我尝试使用let variable,但它不会移动marker。
tl:drScreen.js
import React from 'react';
import {StyleSheet, View} from 'react-native';
import MapView, {Marker, PROVIDER_GOOGLE} from 'react-native-maps';
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
height: 400,
width: 400,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
});
带有 useState 的 Screen.js(昂贵的重新渲染)
export default function GoSendDestinationDetails() {
const [coordinate, setCoordinate] = React.useState({
latitude: -6.1754,
longitude: 106.8272,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
});
const handleRegionChange = (region) => {
setCoordinate(region);
console.log(region);
};
console.log('re-render');
return (
<View style={styles.container}>
<MapView
provider={PROVIDER_GOOGLE} // remove if not using Google Maps
style={styles.map}
initialRegion={coordinate}
onRegionChange={handleRegionChange}>
<MarkerMemo />
</MapView>
</View>
);
}
我尝试过的:
带有 let 变量的 Screen.js
export default function GoSendDestinationDetails() {
let coordinate = {
latitude: -6.1754,
longitude: 106.8272,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
};
const handleRegionChange = (region) => {
coordinate = region;
console.log(region);
};
// this does not update the marker when coordinate changes
const MarkerMemo = React.memo(() => <Marker coordinate={coordinate} />)
console.log('re-render');
return (
<View style={styles.container}>
<MapView
provider={PROVIDER_GOOGLE} // remove if not using Google Maps
style={styles.map}
initialRegion={coordinate}
onRegionChange={handleRegionChange}>
<MarkerMemo />
</MapView>
</View>
);
}
【问题讨论】:
标签: javascript react-native google-maps react-native-maps