首页 > 解决方案 > 如何使用 React Native 访问对象的属性?

问题描述

使用 React Native 时,无法访问brand我的对象的属性,当然还有 less brand.name

有谁知道可能会发生什么?谢谢

代码:

<CardItem bordered style={ styles.cardItem }>
    <Text style={{ padding:20 }} >{this.state.beer.brand.name}</Text>
 </CardItem>

目的:

控制台上的对象

标签: javascriptreactjsreact-native

解决方案


您应该在直接访问嵌套键之前进行条件检查

就像是

  const { beer } = this.state;
 return(
     <div>
         <CardItem bordered style={ styles.cardItem }>
              {beer && beer.brand && <Text style={{ padding:20 }} >{ beer.brand.name}</Text>}
         </CardItem>
     </div>
    )

推荐阅读