参考:How do i update marker position without re rendering mapview ? React native maps
我的目标是防止当用户拖动地图时重新渲染,同时也更改市场坐标。当前的解决方案是使用useState
挂钩。但它会导致组件重新渲染,从而导致应用程序延迟。
我尝试使用let variable
,但它不能移动marker
。
tl:dr
Screen.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>
);
}
发布于 2021-01-05 17:14:32
useState
钩子为您提供了两样东西:
API中持续存在,以更新该值,然后触发一个API
如果你有一个不关心重新渲染的用例,但是你确实需要在渲染之间持久化值,那么你需要一半的useState
来让你在渲染之间持久化值,而不是触发重新渲染的另一半。
而这正是useRef
所做的
useRef()钩子不仅仅适用于DOM引用。“ref”对象是一个通用容器,它的current属性是可变的,可以保存任何值
https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
https://stackoverflow.com/questions/64067595
复制相似问题