我需要检索names of the books written by a particular author
,其中author name
通过get
请求提供的。
我的 API 工作正常并检索相关数据。在这种情况下,我正在获取 more than one book
的 API 响应 JSON。
接口响应 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()
时,响应数据也成功地将相关数据输出为:
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((。
由于您有任何数组,因此您需要指定所需的元素或映射到数组上。
console.log(this.state.data[0].name);
// or to log all names
this.state.data.map(item => console.log(item.name));