【问题标题】:react render Logical && vs Ternary operator反应渲染逻辑 && vs 三元运算符
【发布时间】:2021-04-19 03:28:41
【问题描述】:

render() 的反应中,当 x 的值等于 1 时,逻辑 && 和三元运算符都将显示 Hello 并且两者在语法上都是正确的。当我不想显示我的条件的 else 部分时,我总是使用 &&,但我遇到了一个代码库,其中大多数地方使用三元运算符 null 而不是 &&。使用一种方法相对于另一种方法是否有任何性能提升或任何其他优势?

return (
    <div>
        <div>{x === 1 && <div>Hello</div>}</div>
        <div>{x === 1 ? <div>Hello</div> : null}</div>
    </div>
);

【问题讨论】:

  • 如果您的条件使用严格(或松散比较),那么您可以使用 &amp;&amp; 运算符。如果您只是检查一个真实值,例如x &amp;&amp; &lt;div&gt;Hello&lt;/div&gt; 如果x 可能最终使用该值,您将呈现0。一个常见的场景是检查数组的长度,如果是空数组,您可能不想渲染任何东西,但最终会渲染 0

标签: javascript reactjs jsx conditional-operator


【解决方案1】:

有没有性能提升

答案是否定的。

在 React Js 中,它被称为[Inline If with Logical && Operator]

之所以有效,是因为在 JavaScript 中,true && 表达式的计算结果始终为 表达式,而 false && 表达式的计算结果始终为 false。

因此,如果条件为真,“&amp;&amp;”之后的元素将 出现在输出中。 如果为 false, React 将忽略并跳过它。

【讨论】:

    【解决方案2】:

    没有显着的性能差异,但是因为 0 和空字符串 """falsy" in JavaScript 我总是选择三元运算符,所以下一个编辑我的代码的人知道我的确切意图。

    例子:

    const count: number | null = 0;
    const firstName: number | null = "";
    
    return (
        <div>
            {/* Was this a bug or is `0` really not supposed to render??
              * This will just render "0". */}
            <div>{count && <>The count is {count}</>}</div>
    
            {/* Okay got it, there's a difference between `null` and `number` */}
            <div>
              {count == null ? <>No count at all</> : <>Count of {count}</>}
            </div>
    
            {/* Was this a bug too or is `""` supposed to render nothing?
              * This will just render an empty string. */}
            <div>{firstName && <>My name is {firstName}</>}</div>
    
            {/* Okay now I see `null` / `undefined` vs. a string */}
            <div>
              {firstName == null ? <>No name</> : <>This *will* render {firstName}</>}
            </div>
        </div>
    );
    
    

    【讨论】:

      【解决方案3】:

      没有性能提升,只是易于格式化。

          <div>
              <div>
                  {x === 1 ? (
                     <div>Hello</div>
                  ): null}
              </div>
          </div>
      

      如果你想稍后处理else部分,请稍作修改

          <div>
              <div>
                  {x === 1 ? (
                     <div>Hello</div>
                  ): (
                     <div>just change here.</div>
                  )}
              </div>
          </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-24
        • 2014-03-18
        • 1970-01-01
        相关资源
        最近更新 更多