首页 > 解决方案 > 如何将此代码转换为辅助函数?

问题描述

我正在尝试将这段可能通过使用 switch 语句而不是 if 语句来改进的条件代码转换为辅助函数,以最小化我当前在组件中拥有的代码量。如何在新文件中执行此操作并将其导入到我的组件中?

import { USER_TYPES } from '../../constants/user';

const usertypeToName = {
1: 'client',
2: 'supportWorker',
3: 'accountManager',
 };

 if (this.$route.params.userType === usertypeToName[1]) {
      return USER_TYPES.client;
    }
    if (this.$route.params.userType === usertypeToName[2]) {
      return USER_TYPES.supportWorker;
    }
    if (this.$route.params.userType === usertypeToName[3]) {
      return USER_TYPES.accountManager;
    }
    return 0;

标签: javascriptreactjsvue.jshelper

解决方案


您应该简单地拥有usertypeToNameas 数组,然后使用find

import { USER_TYPES } from '../../constants/user';

const usertypeToName = ['client', 'supportWorker','accountManager']
// find key
const key = usertypeToName.find(v=> v === this.$route.params.userType)
// use dynamic property accessor
return key ? USER_TYPES[key] : 0

推荐阅读