javascript - React:如何在数据的 fromat 中呈现 API 响应数据:Array(i) 以响应前端?
问题描述
我需要检索通过请求提供的names of the books written by a particular author
位置。author name
get
我的 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", …}
任何人都可以建议一种合适的方法来输出这些值以响应前端吗?提前致谢。
解决方案
您不需要 .toString()。
由于您有任何数组,因此您需要指定您想要的元素或映射到数组上。
console.log(this.state.data[0].name);
// or to log all names
this.state.data.map(item => console.log(item.name));
推荐阅读
- linux - 搜索数字对时出现 grep 错误
- .net - Kubernetes .NET 应用程序 SocketExceptionFactory+ExtendedSocketException
- c - 使用不同大小的 fo 跳转并在 MPI_Scatter 上发送数据
- php - Laravel reCAPTCHA 未定义索引:127.0.0.1
- python - Scrapy没有得到
- python - 防止 pandas 将 datetime 对象转换为 pandas Timestamps
- javascript - javascript 中少于 5 行的 RGB 到 Hex 转换器
- mysql - 如何在 sql 中使用 YEARWEEK 获取前一周?
- acumatica - 为什么我的弹出面板没有显示我的控件?
- function - 如何制作验证名字和姓氏输入的函数 - Kotlin