首页 > 解决方案 > TS 缩短代码并在 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}} 
                
            }

代码中有很多重复,所以我想问是否有办法缩短该表达式,例如使用 lambda 表达式。

标签: reactjstypescript

解决方案


不完全确定你想要什么,但在我看来你想source根据value. 我认为这可能是您正在寻找的:

source = when(value) {
    "valA" -> "sourceA"
    "valB" -> "sourceB"
    else -> "undefined"
}

推荐阅读