React showing 0 instead of nothing with short-circuit (&&) conditional component

后端 未结 3 1510
闹比i
闹比i 2020-12-13 05:42

I have the following simple short-circuit statement that should show either a component or nothing:

{profileTypesLoading && }

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 06:27

    0 is a falsy value, so when it is evaluated by &&, it returns 0. However, 0 is renderable by React because it is a number:

    // Renderable values
    1 &&  // => Renders 
    "a string" &&  // => Renders 
    0 &&  // => Renders '0'
    
    // Non-renderable values
    false &&  // => Renders nothing
    null &&  // => Renders nothing
    undefined &&  // => Renders nothing
    

    TLDR

    This is because of how javascript itself process [truthy and falsy values][1]:

    In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

    When used with the && operator, the returned value depends on the left value:

    • If the left value is truthy, the right value is returned.
    • If the left value is falsy, its value is returned.

    Examples:

    // Truthy values
    1 && "hello" // => "hello"
    "a string" && "hello" // => "hello"
    
    // Falsy values
    0 && "hello" // => 0
    false && "hello" // => false
    null && "hello" // => null
    undefined && "hello" // => undefined
    

    The same rules applies to JSX because it is [a syntax extension to JavaScript][2]. However, the issue is that **

    The issue is that 0 is a falsy value, so when it is evaluated by &&, it returns 0. However, 0 is renderable by React because it is a number

    // Renderable values
    1 &&  // => Renders 
    "a string" &&  // => Renders 
    0 &&  // => Renders 0
    
    // Non-renderable values
    false &&  // => Renders nothing
    null &&  // => Renders nothing
    undefined &&  // => Renders nothing
    

提交回复
热议问题