首页 > 解决方案 > 迭代 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 />屏幕上成功渲染。

那么,为什么迭代地图以显示所有图标不起作用?

标签: react-nativereact-native-androidreact-native-ios

解决方案


问题是你没有从 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>;
  });
};

推荐阅读