Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

reactjs - 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}
        />
      );
question from:https://stackoverflow.com/questions/65933298/javascript-react-js-refactor-a-switch-case

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...