我正在尝试弄清楚逻辑,但我有些困惑。我有一系列看起来像这样的对象。
{
"id": 5,
"name": "Mole's Town",
"lat": 33,
"lng": 18.5,
"type": "village"
}
有几种不同的类型,共有九种。村庄,城镇,城市等。我正在尝试为这九种类型中的每种类型创建一个组件,然后将与该特定类型匹配的所有对象过滤到适当的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>
)
答案 0 :(得分:1)
您可以创建一个对象,以将每种类型与相应的组件进行映射。这样的事情会起作用:
for touch in touches {
let pointOfTouch = touch.location(in: view)
}
另一种可能性如下:
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}
/>
);
});
通过这种方式,您将收到位置对象键值对作为属性。
此外,您可能具有默认组件,因为location.type不能是layerComponentsByType的属性:
<LayerControl
key={location.id}
{...location}
/>
答案 1 :(得分:1)
您可以使用Set
在数组中查找所有唯一类型:
const data = [
{
"id": 5,
"name": "Mole's Town",
"lat": 15,
"lng": 18.5,
"type": "village"
},
{
"id": 783,
"name": "Mole's Town",
"lat": 3,
"lng": 18.5,
"type": "village"
},
{
"id": 75,
"name": "Mole's Town",
"lat": 33,
"lng": 8.55,
"type": "town"
},
{
"id": 43,
"name": "Mole's Town",
"lat": 33,
"lng": 15,
"type": "city"
},
{
"id": 443,
"name": "Mole's Town",
"lat": 35,
"lng": 725,
"type": "city"
},
{
"id": 4543,
"name": "Mole's Town",
"lat": 76,
"lng": 2,
"type": "city"
}
]
const types = [...new Set(data.map(loc => loc.type))]
console.log(types)
一旦有了它们,就可以在渲染功能中使用LayerControl
映射它们,同时过滤具有相同类型的每个位置并将其作为道具发送:
types.map(type => <LayerControl key={type} locations={data.filter(loc => loc.type === type)}/>)
然后在您的LayerControl
呈现器中,将每个接收到的位置映射到您在问题中提供的代码:
this.props.locations.map(({id, lat, lng, name}) => //Deconstructing every location to make your code more readable
<Marker key={id} position={[lat, lng]} icon=
{locationIcon}>
<Tooltip permanent direction="bottom" opacity={.6}>
{name}
</Tooltip>
</Marker>
)