0

我正在使用 react-leaflet 和 leaflet.markercluster 创建自定义 MarkerCluster 组件。这个想法是将标记作为子级传递给 MarkerCluster 组件。标记也是 React 组件。我想动态更新我的标记,这意味着将删除一些标记并将其添加到标记数组中/从标记数组中添加并呈现为子项。LocationMarkers 是一个 JSX.Elements 数组

<MarkerCluster maxClusterRadius={100} showCoverageOnHover={false}>
  {locationMarkers}
</MarkerCluster>

删除标记会从地图上直观地删除它,直到我重新添加它。之后出现两个标记而不是一个。集群图标也显示错误的计数,从不减少,一直在增加。提供的代码是预期的行为吗?我尝试在每次更新后使用 new L.Marker() 清除图层并创建标记并且它有效,但我想保留在 Map 组件中渲染的标记并将它们作为子标记在 MarkerCluster 标记之间传递。

import { PropsWithChildren } from "react";

import "leaflet.markercluster";
import L, { MarkerClusterGroupOptions } from "leaflet";

type MarkerClusterProps = PropsWithChildren<MarkerClusterGroupOptions>;


const createMarkerCluster = ({ children, ...props }: MarkerClusterProps, context: LeafletContextInterface) => {
  const instance = new L.MarkerClusterGroup(props);
  return { instance, context: { ...context, layerContainer: instance } }
}

const updateMarkerCluster = (instance: L.MarkerClusterGroup, props: MarkerClusterProps, prevProps: MarkerClusterProps) => {
  if (prevProps.children !== props.children) {
    // What should go here?
  }


}

const MarkerCluster = createPathComponent(createMarkerCluster, updateMarkerCluster);

export default MarkerCluster;

PS 我已经看到像在每次渲染时为 MarkerCluster 组件提供唯一键这样的解决方案,因此它会完全重新渲染,但这会使所有地图闪烁片刻,我想这不是提高性能的最佳方式。

4

0 回答 0