react-native - 迭代 Map 的值以渲染所有图标组件但不起作用但是渲染一个图标有效
问题描述
我正在开发 react-native 项目。
我有一个将图标元数据设置为Map
:
export function getIconsMetadata() {
// a map of icons' metadata
const iconsMetadata = new Map();
...
// code to set icon metadata to the map
iconsMetadata.set("foo", "Foo");
iconsMetadata.set("bar", "Bar");
...
return iconsMetadata;
}
还有另一个函数根据图标类型返回实际的图标组件(即iconsMetadata
保存图标类型的值):
export function getMyIcon(iconType) {
switch (iconType) {
case 'Foo':
return <Foo />;
case 'Bar':
return <Bar />;
...
}
在我的屏幕中,我有一个功能可以通过迭代上述图标的 metadata 的值来显示图标组件Map
,并尝试渲染每个图标组件:
export const MyScreen() => {
const showIcons = () => {
[...getIconsMetadata().values()].map((iconType, index) => {
const iconComponent = getMyIcon(iconType);
return <View key={index}>
{iconComponent}
</View>;
});
};
return (
<View style={styles.container}>
{/*I call the showIcons function here to render icons*/}
{showIcons()}
</View>
)
}
问题是图标未显示在屏幕上。
但是如果我直接在我的屏幕中返回一个图标组件:
export const MyScreen = () => {
...
const showOneIcon = () => {
return <View>
<Foo />
</View>;
});
}
return (
<View style={styles.container}>
{/*I show one icon*/}
{showOneIcon()}
</View>
)
}
图标组件在<Foo />
屏幕上成功渲染。
那么,为什么迭代地图以显示所有图标不起作用?
解决方案
问题是你没有从 showIcons 返回任何东西。从那里删除 { }
const showIcons = () =>
[...getIconsMetadata().values()].map((iconType, index) => {
const iconComponent = getMyIcon(iconType);
return <View key={index}>{iconComponent}</View>;
});
或在之前添加返回[...getIconsMetadata().values()].map
const showIcons = () => {
return [...getIconsMetadata().values()].map((iconType, index) => {
const iconComponent = getMyIcon(iconType);
return <View key={index}>{iconComponent}</View>;
});
};
推荐阅读
- c++ - 当我尝试切换断点 C++ 时,nsi.pdb 无法加载符号错误
- powershell - 在 AD 导出之前将一项转换为小写
- publish - 如何在自动“发布”并在 Google Play 上显示之前将新应用“推出”到内部测试人员列表?
- excel - 减去两个范围值以匹配excel
- c# - 如何使用 EF Core 和 NET Core 2.1 正确播种数据?
- asynchronous - Cassandra 异步读写,最佳实践
- javascript - 触发来自 iframe 中存在的父级的按钮单击
- java - JSch:从存储在 hdfs 上的私钥添加身份
- python - 格式化由两列分组的熊猫数据系列,并在第三个重新采样,平均值为 dict
- java - 无法从集群网络外部的 Java 应用程序获取 HDFS 集群中文件的 InputStream