我需要检索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", …}
任何人都可以建议一种合适的方法来输出这些值以对前端使用react吗?提前致谢。
最佳答案
您不需要 .toString()。
由于您有任何数组,因此您需要指定所需的元素或映射到数组。
console.log(this.state.data[0].name);
// or to log all names
this.state.data.map(item => console.log(item.name));
关于javascript - react : How to render API response data in fromat of data: Array(i) to react front end?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56436527/