react渲染逻辑&& vs 三元运算符

IT技术 javascript reactjs jsx conditional-operator
2021-05-23 23:56:03

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

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

没有显着的性能差异,但是因为0空字符串在 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>
);

是否有任何性能提升

答案是不。

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

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

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

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

    <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>