【问题标题】:How can i turn this code into a helper function?如何将此代码转换为辅助函数?
【发布时间】:2020-04-26 09:02:44
【问题描述】:

我正在尝试将这段可能通过使用 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;

【问题讨论】:

  • 你可以直接做userToName[$route.params.userType] ?? 0,不需要在那里手动检查所有的键。
  • @TheFool 可能存在userToName[$route.params.userType] 其他虚假值的情况,假设存在一个名为default 的键,但只想访问给定的键,否则返回0,在这种情况下,上述情况将不工作

标签: javascript reactjs vue.js helper


【解决方案1】:

您应该简单地将usertypeToName 作为数组,然后使用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

【讨论】:

    【解决方案2】:

    这是你要找的吗?

    ## util.js
    
    import { USER_TYPES } from '../../constants/user';
    
    const userTypeMap = {
      client: USER_TYPES.client,
      supportWorker: USER_TYPES.supportWorker,
      accountManager: USER_TYPES.accountManager,
    };
    
    export function mapUserType(name) {
      // Fallback to 0 incase mapping does not exist
      return userTypeMap[name] || 0
    }
    
    
    ## component.js
    
    import { mapUserType } from './util.js'
    
    const userType = mapUserType(this.$route.params.userType)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 2014-10-02
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多