【问题标题】:How to simplify if statement in react? [closed]如何简化反应中的if语句? [关闭]
【发布时间】:2020-11-02 22:07:02
【问题描述】:

如何在 React 中简化这个三元表达式?

{dataIndex ? (
    <>{!obj[i] ? 'N/A' : <>{obj[i][dataIndex] ? obj[i][dataIndex] : 'N/A'}</>}</>
) : (
    <>{!obj[i] ? 'N/A' : obj[i]}</>
)}

显然它太复杂了,我需要简化它。有什么建议吗?也许也没有碎片

【问题讨论】:

    标签: javascript reactjs logic


    【解决方案1】:

    使用可选链和|| 代替条件运算符:

    {dataIndex ? (
      obj[i]?.[dataIndex] || 'N/A'
    ) : (
      obj[i] || 'N/A'
    )}
    

    请注意,无需将结果表达式包围在 &lt;&gt; 片段中 - 单独使用表达式本身就足够了。

    如果查找dataIndex 属性是可以的,即使dataIndex 是错误的——这很可能是可以的,除非你有非常奇怪的getter——这可以简化为

    { obj[i]?.[dataIndex] || obj[i] || 'N/A' }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 2021-11-20
      • 2014-06-18
      • 2018-12-01
      • 2021-12-07
      相关资源
      最近更新 更多