如何避免代码中出现嵌套的三元表达式?

新手上路,请多包涵

我有这样的代码。我如何使用 JavaScript 中的函数式编程以更简洁、更优雅的方式编写它?我想摆脱嵌套的三元表达式。有任何想法吗?

 props => ({
            iconColor: props.isPriority ? (props.isCompleted ? variables.color.lightpurple : variables.color.purple ) : variables.color.gray3,
            iconName: props.isPriority ? 'star-full' : 'star-empty',
          }))

这是该代码的其余部分:

编辑:

 const enhance: React$HOC<*, InitialProps> = compose(
      withProps(props => ({
        iconColor: props.isPriority ? (props.isCompleted ? variables.color.lightpurple : variables.color.purple) : variables.color.gray3,
        iconName: props.isPriority ? 'star-full' : 'star-empty',
      }))
    )

原文由 MountainConqueror 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 799
2 个回答

是的,但我的 linter 不开心: 44:16 error Do not nest ternary expressions [no-nested-ternary]

如果那是您唯一的问题,那么解决方案很简单。创建您自己的条件函数:

 const iff = (condition, then, otherwise) => condition ? then : otherwise;

props => ({
  iconColor: props.isPriority ?
    iff(props.isCompleted, variables.color.lightpurple, variables.color.purple) :
    variables.color.gray3,
  iconName: props.isPriority ? 'star-full' : 'star-empty',
})

现在你的 linter 不应该抱怨了。话虽如此,您应该在 linter 中禁用 [no-nested-ternary] 。你的 linter 认为嵌套条件语句不好,这有点愚蠢。

原文由 Aadit M Shah 发布,翻译遵循 CC BY-SA 3.0 许可协议

我会建议,只需在下面使用:

     props => ({
      iconColor: ${(props) => {
      if (props.isPriority) {
        return props.isCompleted
          ? variables.color.lightpurple
          : variables.color.purple;
      }
      return variables.color.gray3;
    }};
      iconName: props.isPriority ? 'star-full' : 'star-empty',
    })

原文由 vipul goyal 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题