有没有办法在不重新渲染的情况下更改react-native-maps <Markerordinate = {coordinate} /> API坐标?

问题描述

参考:Mongo playground

我的目标是防止用户拖动地图时重新渲染,同时还要更改市场坐标。当前的解决方案是使用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,};
  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>
  );
}

解决方法

useState Hook 为您提供两件事:

  • 一个将在渲染中持续存在的值
  • 用于更新该值并触发重新渲染的 API。

如果您有一个不关心重新渲染的用例,但您确实需要跨渲染保留一个值,那么您需要 useState 的一半,它可以让您跨渲染保留一个值,但是不是触发重新渲染的另一半。

这正是useRef所做的

useRef() 钩子不仅仅用于 DOM 引用。 “ref”对象是一个通用容器,它的当前属性是可变的,可以保存任何值

https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables