首页/ AI 技能 / @skilllib/skill-2014279386374025219
Skill站外收录 @skilllib/skill-2014279386374025219

rendering-conditional-render

在 React 中对可能为 0、NaN 等 falsy 值的条件进行渲染时,应使用三元运算符而非逻辑与(&&),避免意外输出 0 或其他 falsy 值内容,确保渲染行为符合预期。

0.0 (0) 216 次安装 原作者 编程导航
收录于 2026-01-22
软件开发 AI 技能

Skills.MD

## Use Explicit Conditional Rendering Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render. **Incorrect (renders "0" when count is 0):** ```tsx function Badge({ count }: { count: number }) { return ( <div> {count && <span className="badge">{count}</span>} </div> ) } // When count = 0, renders: <div>0</div> // When count = 5, renders: <div><span class="badge">5</span></div> ``` **Correct (renders nothing when count is 0):** ```tsx function Badge({ count }: { count: number }) { return ( <div> {count > 0 ? <span className="badge">{count}</span> : null} </div> ) } // When count = 0, renders: <div></div> // When count = 5, renders: <div><span class="badge">5</span></div> ```

评论 0

还没有评论,来抢沙发。