react-native - axios 响应返回对象而不是数组
问题描述
我在本机反应中使用 axios。邮递员的原始响应如下所示:
{
"id": 2,
"parent_id": 1,
"name": "Default Category",
"is_active": true,
"position": 1,
"level": 1,
"product_count": 2,
"children_data": [
{
"id": 3,
"parent_id": 2,
"name": "Papers",
"is_active": true,
"position": 1,
"level": 2,
"product_count": 2,
"children_data": [
{
"id": 5,
"parent_id": 3,
"name": "A44",
"is_active": true,
"position": 1,
"level": 3,
"product_count": 0,
"children_data": []
}
]
},
{
"id": 6,
"parent_id": 2,
"name": "Laptop",
"is_active": true,
"position": 2,
"level": 2,
"product_count": 1,
"children_data": []
}
]
}
当我尝试这个时,我如何 console.log(typeof categoryResponse.data.children_data);
得到对象。这会导致问题,因为我正在尝试更新类型数组的 react-native 中的状态变量。甚至打印时的响应对象 console.log(categoryResponse.data);
看起来也很奇怪。
对象{“children_data”:数组[对象{“children_data”:数组[对象{“children_data”:数组[],“id”:5,“is_active”:真,“级别”:3,“名称”:“A44 ", "parent_id": 3, "position": 1, "product_count": 0, }, ], "id": 3, "is_active": true, "level": 2, "name": "Papers", "parent_id": 2, "position": 1, "product_count": 2, }, Object { "children_data": Array [], "id": 6, "is_active": true, "level": 2, "name": "Laptop", "parent_id": 2, "position": 2, "product_count": 1, }, ], "id": 2, "is_active": true, "level" :1,“名称”:“默认类别”,“parent_id”:1,“位置”:1,
"product_count": 2, }
请帮忙
解决方案
在 javascript 中,typeof 数组实际上是一个对象。在 javascript 中只有 6 种数据类型。数组是 objects 的子集,因此console.log(typeof categoryResponse.data.children_data)
即使它是一个数组也会返回 object。
但你可以看到,当console.log(categoryResponse.data)
你看到
Object { "children_data": Array [ Object { "children_data": Array [ Object { "children_data": Array [], "id": 5, "is_active": true, "level": 3, "name": "A44", "parent_id": 3, "position": 1, "product_count": 0, }, ], "id": 3, "is_active": true, "level": 2, "name": "Papers", "parent_id": 2, "position": 1, "product_count": 2, }, Object { "children_data": Array [], "id": 6, "is_active": true, "level": 2, "name": "Laptop", "parent_id": 2, "position": 2, "product_count": 1, }, ], "id": 2, "is_active": true, "level": 1, "name": "Default Category", "parent_id": 1, "position": 1,
"product_count": 2, }
在这里你可以看到“childern_data”作为一个数组。
"children_data": Array [ Object {
所以基本上它是一个数组,不要让 typeof 混淆你。
希望能帮助到你。随意怀疑,我会清除它
推荐阅读
- python - Xlwings:如何将单个单元格中的两个逗号分隔值作为列表而不是浮点数读取?
- entity-framework - 如何通知用户在他缺席期间所做的所有更改
- bash - 如何编写一个 bash 脚本来退出程序?
- python - 使用matplotlib(python)在boxplot中添加补丁
- python - 我如何遍历每一行,并为每一行将结果附加到一个列表中?
- typescript - 具有多个参数的函数接口?
- python - 如何在字典的嵌套列表中获取随机项?
- docker - worldserver Docker 容器的日志文件在哪里?
- kubernetes - gRPC 客户端负载均衡
- python - 找到单词之间的余弦相似度