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

标签 javascript reactjs jsx conditional-operator

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

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

最佳答案

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

关于javascript - react 渲染逻辑 && vs 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65713434/

相关文章:

javascript - 更新 : AndroidTextInput 管理的 View 的属性 'placeholder' 时出错

reactjs - Visual Studio Code 中的 JSX 或 HTML 自动完成

javascript - 尝试使用 2d 数组起草 6x6 游戏板

javascript - 单击验证链接后,Firebase 将用户重定向到页面

javascript - 嵌套 ng-repeat 无法正常工作

javascript - 如何在 CSS 中将元素的宽度设置为等于高度的 10%?

javascript - 如何使用 Firestore 在快照上按值排序

javascript - 使用 Reactjs 进行网页抓取

javascript - 取消拖动或禁用重新排序

reactjs - 如何获取 React 中 select-option 的值?