首页 > 解决方案 > React:如何在数据的 fromat 中呈现 API 响应数据:Array(i) 以响应前端?

问题描述

我需要检索通过请求提供的names of the books written by a particular author位置。author nameget

我的 API 工作正常并检索相关数据。在这种情况下,我将获取more than one book.

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},但它不输出书名。但是,当 I 时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", …}

任何人都可以建议一种合适的方法来输出这些值以响应前端吗?提前致谢。

标签: javascriptreactjsaxios

解决方案


您不需要 .toString()。

由于您有任何数组,因此您需要指定您想要的元素或映射到数组上。

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

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

推荐阅读