简体   繁体   中英

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

I am creating a tab navigator which listen to my database and renders 5 different icons, one of them with a badge.

Currenlty, I am making this with a switch-case, to avoid returning the same component with different props 5 times. But the reallity is that it doesn't look really professional. Any design pattern to refactor this code?

      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}
        />
      );

This how I would do it:

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:

You can use a design like this

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

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

You can check the links below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM