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

时间:2018-11-16 15:41:24

标签: javascript reactjs

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

  

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"
        }
    ]
}

当我在代码中将此对象声明为常量时,它没有返回任何错误,并且映射有效。但是,当我尝试分配results中的data时将无法使用。

1 个答案:

答案 0 :(得分:2)

要正确执行此操作,您应该在Promise链中调用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()的函数在您的类中。您可以使用全局函数来执行所需的操作,但这要复杂一些。基本的想法是一样的。