Javascript (React.js) - 重构一个 switch-case

Javascript (React.js) - Refactor a switch-case

我正在创建一个选项卡导航器,它会监听我的数据库并呈现 5 个不同的图标,其中一个带有徽章。

Currenlty,我正在用一个 switch-case 做这个,以避免用不同的道具返回相同的组件 5 次。但事实是它看起来并不专业。重构此代码的任何设计模式?

      let iconName;
      let iconType = "material-community"; // app default icons from material-community
      let badgeNumber;

      switch (route.name) {
        case "Home":
          iconName = "home";
          break;

        case "Interactions":
          iconName = "heart";
          badgeNumber = props.notifications;
          break;

        case "Camera":
          iconName = "camera";
          break;

        case "Search":
          iconName = "search";
          iconType = "material";
          break;

        case "Profile":
          iconName = "person";
          iconType = "material";
          break;
      }

      return (
        <BadgedIcon
          number={badgeNumber} 
          name={iconName}
          type={iconType}
          color={color}
          size={24}
          badgeStyle={styles.interactionsBadge}
        />
      );

我会这样做:

const iconMap = {
  Home: {
    iconName: 'home',
    iconType: 'material',
    badgeNumber: props.notifcations
  },
  /// All your other route names:
}

return (
<BadgedIcon
number = { iconMap[router.name].badgeNumber }
name = {iconMap[router.name].iconName}
// All your other props:

你可以使用这样的设计

 const iconName = {
    Home: 'home',
    Interactions: 'heart',
    Camera: 'camera',
    Search: 'search',
    Profile: 'person'
  };

function geticonName(route.name) {
  return iconName[route.name];
}

您可以查看以下链接

https://dev.to/nyagarcia/the-art-of-refactoring-5-tips-to-write-better-code-12if https://github.com/KarlPurk/javascript-refactoring/blob/master/patterns/javascript/replace-switch-with-object-literal.md