我无法从对象中获取值。获取未定义的对象错误

I am unable to get the value from the object. Getting undefined object error

我是 React Native 的新手,我想获取对象值并将其打印在文本中,但我得到 undefined is not an object (evaluating 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>
  );
}

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

这是由于 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>
    );
  }

您似乎正在尝试获取一组数据并使用它创建一个使用该数据的新组件数组。使用 for 循环可能会非常笨重且难以阅读,所以我认为您应该使用 map 函数。

我会这样解决:

// this.state.typeofCountry is an array so we 
// can use the map function to iterate over it.
// The callback function passes each entry of the array as a parameter, 
// you can name this parameter anything you want!

this.state.typeofCountry.map((country) =>  (
    <View>
       <Text >
       {country.label}
      </Text>
     </View>
))

要阅读有关 map 和其他真正有用的数组函数的更多信息,我建议您前往 MDN 看看您还可以使用什么。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

希望对您有所帮助,编码愉快!