首页 > 解决方案 > 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, }

请帮忙

标签: react-nativeaxios

解决方案


在 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 混淆你。

希望能帮助到你。随意怀疑,我会清除它


推荐阅读