Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react 遇到短路操作的渲染问题 #4

Open
JslinSir opened this issue Apr 25, 2022 · 0 comments
Open

react 遇到短路操作的渲染问题 #4

JslinSir opened this issue Apr 25, 2022 · 0 comments
Labels
react react 相关问题

Comments

@JslinSir
Copy link
Owner

JslinSir commented Apr 25, 2022

react 遇到短路操作的渲染问题

问题产生

今天组内同学发现了个问题,代码如下:

   {
       0 && <div>xxxx<div> 
   }

这种短路操作符写法,如果第一个为 假,则返回 第一个值,所以页面就会渲染 0

产生原因

  • react 中的 jsx 是一个 表达式,当采用 短路写法的时候 如果的一个 值为 0 为假,则 会返回 0

  • a && b ,如果a 我假,则返回 a

  • a && b ,如果b 我假,则返回 b

    如何规避?

    • 尽量用三目运算符书写
    • 如果想用这种短路写法,需要明确几点:

    数组,最好 list.length>0 && <>xxxx</>
    数字, 最好 String(a) && <>xxxx</>
    字符串为空,就渲染空,可以不做处理
    对象 总为真

@JslinSir JslinSir added the react react 相关问题 label Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
react react 相关问题
Projects
None yet
Development

No branches or pull requests

1 participant