我无法理解如何使用 react-leaflet 正确更新我的标记。使用这个例子:
import React from 'react';
import { render } from 'react-dom';
import { connect } from 'react-redux';
import { Map, Marker, TileLayer } from 'react-leaflet';
const map = props => (
<Map center={[51.505, -0.09]} zoom={13}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{props.markers.map(m => (
<Marker position={m.position} />
))}
</Map>
);
const mapStateToProps = state => ({
markers: state.markers // array of objects with positions. this can change
});
render(connect(mapStateToProps)(map), document.getElementById('map-container'));
这有效,但我不知道这是否是正确的做法。因为在这种情况下,当标记更新其位置(或有更多标记)时,Leaflet 将删除标记并放置新标记,而不是更新原始标记的位置。
所以我的问题是。我做得对还是这不是最高效的方式?
谢谢!
最佳答案
Am I doing it right?
是的,你是。你应该这样使用它。
this is not the most performant way
你也在那里。 这不是最高效的方式 .这是因为一旦 props 发生变化,就会强制重新渲染 react 组件。这将包括移除存在的标记和添加所有新标记。这是因为 React 不会知道什么是来自之前的 props 以及什么是新的东西。
您可以使用 keys 解决此问题在映射您的数据时。阅读更多相关信息 here
另一种方法是计算您的
addedMarkers
, removedMarkers
和 updatedMarkers
并使用它们重新渲染您的 View 。但是,如果您的应用程序要使用的标记数量相当少,这可能会成为一个大麻烦。
关于reactjs - React-leaflet:如何更新标记位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59849344/