【问题标题】:React : How to render API response data in fromat of data: Array(i) to react front end?React:如何以数据格式呈现 API 响应数据:Array(i) 以响应前端?
【发布时间】:2019-06-04 02:12:08
【问题描述】:

我需要检索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", …}

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

【问题讨论】:

  • 为什么是.toString()?只需映射this.state.data,即this.data.map(books=> console.log(books.name))

标签: javascript reactjs axios


【解决方案1】:

您不需要 .toString()。

既然你有任何数组,你需要指定你想要的元素或映射到数组上。

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

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

【讨论】:

  • 我很高兴它有帮助:)
猜你喜欢
  • 2019-01-01
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 2014-10-04
  • 1970-01-01
  • 2019-03-15
相关资源
最近更新 更多