首页 > 解决方案 > 我无法从对象中获取值。获取未定义的对象错误

问题描述

我是 React Native 的新手,我想获取对象值并将其打印在文本中,但我得到 undefined is not an object(评估 json['label'])

下面是格式:

[ {"id":"1","label":"abc","icon":{"uri":"imagepath"}}]

所以现在我已经存储它并尝试将标签值保存在变量中。

    for(let i = 0; i < 4; i++){
 const json=this.state.typeofCountry[i];
  const originallable33 = json['label']; 
  marqueeItems.push(
    <View>
       <Text >
       {originallable33}
      </Text>
     </View>
  );
}

如果有人向我解释如何解析数组和对象并从中获取任何特定值,那将非常有帮助。

标签: arraysjsonreact-nativeobjectreact-native-android

解决方案


这是由于this.state.typeofCountry[i]返回未定义(很可能是由于i比数组本身大)

通过添加一个简单的空检查安全地提取项目而没有未定义的错误 -

for(let i = 0; i < 4; i++){
  const json=this.state.typeofCountry[i]; // json could be undefined

  if(json?.label){
    // notice the ?. operator (this is called optional chaining)
    // if true, "label" is present

    const originallable33 = json['label']; 
    marqueeItems.push(
      <View>
       <Text>
         {originallable33}
      </Text>
     </View>
    );
  }

推荐阅读