reactjs - 将 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>
)
解决方案
您可以创建一个对象来将每种类型与相应的组件进行映射。像这样的东西会起作用:
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;
推荐阅读
- ios - 理解 Swift App 中的 SVG 变换矩阵
- python - 如何在python中以给定频率迭代时间戳
- python-3.x - 有人能告诉我如何纠正我的 python 代码中的语法错误和格式吗?我的输出一直说“SyntaxError:无效语法”
- r - 在 R 中,如何根据特定的行/列标准有选择地将一个单元格“复制并粘贴”到另一个单元格中?
- css - React Native 外部样式表不更新组件
- api - MarketStack API 仅返回 IEXG 交换数据
- kaggle - 从 kaggle 下载后文本文件减少(8GB 到 1GB)
- sql - SQL Server - 更改列长度会导致附带损害?
- python - 如何为每一行创建 HTML 表格按钮并将第一列的值输入到 Flask 函数进行查询
- function - 如何将表达式作为文字变量传递给 Julia 中的函数