首页 > 解决方案 > Reactjs:TypeError:无法读取未定义的属性“结果”

问题描述

我正在从一个 Rest API 获取数据,它返回一个带有结果数组的对象。当我尝试通过它进行映射时,它给了我以下错误:

TypeError:无法读取未定义的属性“结果”

function Teste() {
    let results;
    fetch('https://parseapi.back4app.com/classes/MyClass', {
        method: 'GET',
        headers: {
            'X-Parse-Application-Id': 'MyKey',
            'X-Parse-REST-API-Key': 'MyKey',
            'X-Parse-Master-Key': 'MeyKey'
        }
    }).then(response => {
        return response.json();
    }).then(data => {
        results = data;
        console.log(results);
    }).catch(error => {
        console.log(error);
    });

    const mapCats = Object.keys(results.results).map(key => 
        <li key={key}>{results.results[key].name}</li>
    );

    return (
        mapCats
    );
}

结果的输出是这样的:

{
    "results": [
        {
            "objectId": "JoT2miD1vo",
            "name": "Mercado",
            "createdAt": "2018-11-08T13:49:25.600Z",
            "updatedAt": "2018-11-08T13:50:08.721Z"
        },
        {
            "objectId": "DEuZHY7BwY",
            "name": "Panificadora",
            "createdAt": "2018-11-08T13:49:40.385Z",
            "updatedAt": "2018-11-08T17:06:09.129Z"
        },
        {
            "objectId": "V3g1FXNtLK",
            "name": "Farmácia",
            "createdAt": "2018-11-08T13:50:02.293Z",
            "updatedAt": "2018-11-08T13:50:02.293Z"
        },
        {
            "objectId": "Psl9GWqB4F",
            "name": "Loja",
            "createdAt": "2018-11-08T13:50:34.696Z",
            "updatedAt": "2018-11-08T13:50:34.696Z"
        },
        {
            "objectId": "ezlncu6cd1",
            "name": "Lanchonete",
            "createdAt": "2018-11-08T13:50:41.649Z",
            "updatedAt": "2018-11-08T13:50:41.649Z"
        },
        {
            "objectId": "vDgxIW69rr",
            "name": "Sorveteria",
            "createdAt": "2018-11-08T13:50:54.824Z",
            "updatedAt": "2018-11-08T13:50:54.824Z"
        },
        {
            "objectId": "VdxckEDG7q",
            "name": "Food Truck",
            "createdAt": "2018-11-08T13:51:14.096Z",
            "updatedAt": "2018-11-08T13:51:14.096Z"
        },
        {
            "objectId": "LHrGCT9SCs",
            "name": "Pizzaria",
            "createdAt": "2018-11-08T16:12:48.317Z",
            "updatedAt": "2018-11-08T16:12:48.317Z"
        }
    ]
}

当我在代码中将此对象声明为常量时,它不会返回任何错误并且映射有效。但是当我尝试分配它resultsdata它不起作用。

标签: javascriptreactjs

解决方案


要正确执行此操作,您应该调用setState()承诺链。

.then(data => {
    results = data;
    this.setState({results});
    console.log(results);
}

然后您可以<li>在以下位置创建元素render()

render() {
    const mapCats = Object.keys(this.state.results.results).map(key => 
        <li key={key}>{this.state.results.results[key].name}</li>
    );

    // ...
}

请注意,我假设调用的函数fetch()在您的类中。你可以用一个全局函数做你想做的事,但它有点复杂。不过,基本思想是一样的。


推荐阅读