【发布时间】: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