title: 切勿对可能为假值的值使用 &&
impact: CRITICAL
impactDescription: 防止生产环境崩溃
tags: rendering, conditional, jsx, crash

切勿对可能为假值的值使用 &&

当 value 可能为空字符串或 0 时,切勿使用 {value && <Component />}。这些值虽然是假值,但可以被 JSX 渲染——React Native 会尝试将它们作为 <Text> 组件之外的文本渲染,导致生产环境严重崩溃。

错误做法(如果 count 为 0 或 name 为 “” 时会崩溃):

function Profile({ name, count }: { name: string; count: number }) {
  return (
    <View>
      {name && <Text>{name}</Text>}
      {count && <Text>{count} 件商品</Text>}
    </View>
  )
}
// 如果 name="" 或 count=0,渲染假值 → 崩溃

正确做法(使用三元表达式加 null):

function Profile({ name, count }: { name: string; count: number }) {
  return (
    <View>
      {name ? <Text>{name}</Text> : null}
      {count ? <Text>{count} 件商品</Text> : null}
    </View>
  )
}

正确做法(显式布尔转换):

function Profile({ name, count }: { name: string; count: number }) {
  return (
    <View>
      {!!name && <Text>{name}</Text>}
      {!!count && <Text>{count} 件商品</Text>}
    </View>
  )
}

最佳做法(提前返回):

function Profile({ name, count }: { name: string; count: number }) {
  if (!name) return null

  return (
    <View>
      <Text>{name}</Text>
      {count > 0 ? <Text>{count} 件商品</Text> : null}
    </View>
  )
}

提前返回最清晰。当内联使用条件表达式时,优先使用三元表达式或显式布尔检查。

Lint 规则: 启用 eslint-plugin-react 中的 react/jsx-no-leaked-render 规则可自动捕获此问题。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐