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



我是React Native的新手,我想获得对象值并将其打印在Text中,但我得到了未定义的对象不是对象(正在评估json['label'](

以下是格式:

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

for(let i = 0; i < 4; i++){
const json=this.state.typeofCountry[i];
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

希望有帮助,快乐编码!

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

最新更新