reactjs - Typescript - 缩短重复 if 表达式的代码
问题描述
我想缩短我目前看起来像这样的代码:
onClick={value => {
if (value === "valA") {
Mutation.mutate({filter, source: "sourceA" }, {someRepetitiveCode}},
} else if (value === "valB") {
Mutation.mutate({filter, source: "sourceB" }, {someRepetitiveCode}},
else {
Mutation.mutate({filter, source: undefined },{someRepetitiveCode}}
}
代码中有很多重复,所以我想问是否有办法缩短该表达式。
解决方案
您的代码很好,不需要缩短它,但这是一个尝试......
let source = undefined
if (value === "valA") {
source = "SourceA"
} else if (value === "valB") {
source = "SourceB"
}
Mutation.mutate({filter, source},{someRepetitiveCode}}
甚至更短
let source = value === "valA" ? "SourceA"
: value === "valB" ? "SourceB"
: undefined;
Mutation.mutate({filter, source},{someRepetitiveCode}}