React:如何在数据源中渲染API响应数据:Array(i)以响应前端?

时间:2019-06-04 02:12:08

标签: javascript reactjs axios

我需要检索names of the books written by a particular author,其中author name是通过get请求提供的。

我的API可以正常工作并检索相关数据。在这种情况下,我将获得more than one book的API响应JSON。

API响应JSON:

[
    {
        "_id": "5cf40d9d74df260aa460a74b",
        "name": "Oliver Twist",
        "author": "Charles Dickens",
        "yearOfPublication": "1839",
        "__v": 0
    },
    {
        "_id": "5cf4115b4b557126a02c6087",
        "name": "David Copperfield ",
        "author": "Charles Dickens",
        "yearOfPublication": "1850",
        "__v": 0
    },
    {
        "_id": "5cf412c54b557126a02c6088",
        "name": "A Christmas Carol ",
        "author": "Charles Dickens",
        "yearOfPublication": "1843",
        "__v": 0
]

我尝试使用const books = this.state.data.toString();并通过{books.name}访问书名,但是它没有输出书名。但是,当我console.log()时, response.data 也会以如下方式成功输出相关数据:

0: {_id: "5cf40d9d74df260aa460a74b", name: "Oliver Twist", author: "Charles Dickens", …}
1: {_id: "5cf4115b4b557126a02c6087", name: "David Copperfield ", author: "Charles Dickens", …}
2: {_id: "5cf412c54b557126a02c6088", name: "A Christmas Carol ", author: "Charles Dickens", …}

有人能建议一种合适的方法来输出这些值来响应前端吗?预先感谢。

1 个答案:

答案 0 :(得分:1)

您不需要.toString()。

由于具有任何数组,因此需要指定所需的元素或在数组上进行映射。

console.log(this.state.data[0].name);

// or to log all names
this.state.data.map(item => console.log(item.name));