【问题标题】:Is there a way to change react-native-maps <Marker coordinate={coordinate} /> API coordinate without re-rendering?有没有办法在不重新渲染的情况下更改 react-native-maps <Marker coordinate={coordinate} /> API 坐标?
【发布时间】: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


    【解决方案1】:

    useStateHook 给你两件事:

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

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

    这正是useRef 所做的事情

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-05
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2020-08-01
      • 2016-08-01
      • 1970-01-01
      相关资源
      最近更新 更多