首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有一种方法可以在不重新渲染的情况下更改react-native-maps <Marker { there } /> coordinate=坐标?

有没有一种方法可以在不重新渲染的情况下更改react-native-maps <Marker { there } /> coordinate=坐标?
EN

Stack Overflow用户
提问于 2020-09-26 00:01:01
回答 1查看 352关注 0票数 0

参考:How do i update marker position without re rendering mapview ? React native maps

我的目标是防止当用户拖动地图时重新渲染,同时也更改市场坐标。当前的解决方案是使用useState挂钩。但它会导致组件重新渲染,从而导致应用程序延迟。

我尝试使用let variable,但它不能移动marker

tl:dr Screen.js

代码语言:javascript
运行
复制
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 (昂贵的重新渲染)

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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>
  );
}
EN

回答 1

Stack Overflow用户

发布于 2021-01-05 17:14:32

useState钩子为您提供了两样东西:

  • 一个值,该值将在整个re-render.

API中持续存在,以更新该值,然后触发一个API

如果你有一个不关心重新渲染的用例,但是你确实需要在渲染之间持久化值,那么你需要一半的useState来让你在渲染之间持久化值,而不是触发重新渲染的另一半。

而这正是useRef所做的

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64067595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档