arrays - 我无法从对象中获取值。获取未定义的对象错误
问题描述
我是 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>
);
}
如果有人向我解释如何解析数组和对象并从中获取任何特定值,那将非常有帮助。
解决方案
这是由于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>
);
}
推荐阅读
- sql-server - 同一个站点号,是否可以同时列出当前值和两个小时前的值?
- java - 从包含图像标签和开关列表的列表视图中获取开关 ID
- java - Kafka dsl api 开发人员指南中的问题
- kubernetes - 覆盖 PVC 中的 StorageClass 参数
- api - SQL/RPG DB2 i - Systools.HttpPostClob 中的错误
- git - libgit2sharp 在分支之间获取不同的文件,忽略合并将处理的内容
- python - 这个找到最大绝对差的解决方案与我的解决方案有什么关系?
- php - On Redis is better to store one key with JSON data as value or multiple keys with single value?
- ios - 如何在 iOS 中快速使用 UDP 套接字?
- php - 从数据库调用数据作为标题