首页 > 解决方案 > 将 JSON 数据排序然后过滤到单独的组件中

问题描述

我正在尝试找出逻辑,但我有点卡住了。我有一组看起来像这样的对象。

    {
        "id": 5,
        "name": "Mole's Town",
        "lat": 33,
        "lng": 18.5,
        "type": "village"
    }

有几种不同的类型,总共九种。Village、Town、City 等。我正在尝试为这九种类型中的每一种制作一个组件,然后将与该特定类型匹配的所有对象过滤到适当的 LayerControl 组中。

这是我到目前为止所拥有的,但这只是呈现 Marker 组件但没有考虑类型。

  const stuff = data.map((location) =>
        <Marker key={location.id} position={[location.lat, location.lng]} icon= 
           {locationIcon}>
          <Tooltip permanent direction="bottom" opacity={.6}>
            {location.name}
          </Tooltip>
        </Marker>
      )

标签: reactjsfilterleafletcomponentsreact-leaflet

解决方案


您可以创建一个对象来将每种类型与相应的组件进行映射。像这样的东西会起作用:

const LayerVillage = ({ position, name }) => (
  <Marker position={position} icon={locationIcon}>
    <TooltipComponent permanent direction="bottom" opacity={0.6}>
      {name}
    </TooltipComponent>
  </Marker>
);

const layerComponentsByType = {
  village: LayerVillage,
  town: LayerTown
};

const stuff = data.map(location => {
  const LayerControl = layerComponentsByType[location.type];
  return (
    <LayerControl
      key={location.id}
      position={[location.lat, location.lng]}
      name={location.name}
    />
  );
});

另一种可能性如下:

    <LayerControl
      key={location.id}
      {...location}
    />

通过这种方式,您将收到位置对象键值对作为属性。

此外,您可以有一个默认组件,因为 location.type 不能是 layerComponentsByType 的属性:

  const LayerControl = layerComponentsByType[location.type] || DefaultLayerControl;

推荐阅读