reactjs - ReactJS:如何使用数组呈现 JSON 对象
问题描述
我正在尝试将带有数组的对象呈现为从 API 接收的数组(JSON)。我已经尝试了很多,但我没有得到解决方案。
这是我收到的对象格式:
{
"catalogue": [
[
"shoes.txt",
"trousers.txt",
"tshirts.txt"
]
]
}
这是我用来调用 API 和渲染对象的代码:
import React, { Component } from "react";
import axios from "axios";
class Result extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
}
componentDidMount() {
const URL = "http://localhost/catalogue";
fetch(URL)
.then((response) => response.json())
.then((data) => this.setState({ items: data }));
}
render() {
const catalogue = this.state.items.catalogue;
return <div>{catalogue}</div>;
}
}
export default Result;
我唯一能在网上展示的是:
shoes.txttrousers.txttshirts.txt
我能得到的视图是这样的:
shoes.txt
trousers.txt
tshirts.txt
有人会帮我吗?提前致谢。
解决方案
尝试这个:
import React, { Component } from "react";
class Result extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
}
componentDidMount() {
const URL = "http://localhost/catalogue";
fetch(URL)
.then((response) => response.json())
.then((data) => this.setState({ items: data.catalogue[0] }));
}
render() {
let catalogue = this.state.items.map((item, key) => (
<li key={key}>{item}</li>
));
return <ul>{catalogue}</ul>;
}
}
export default Result;
注意这一行中的“[0]”:
.then((data) => this.setState({ items: data.catalogue[0] }));
推荐阅读
- swift - 如何将包含 AAC 数据的 AudioBufferList 转换为 CMSampleBuffer
- flutter - 如何知道页面是否打开/添加到导航器堆栈?
- ios - 如何在调整 inputAccessoryView 大小时解决“API 错误:返回 0 宽度,假设 UIViewNoIntrinsicMetric”?
- com - 未由 Installshield 2015/2018 Express 注册的 COM 服务器库
- ruby - Ruby 可执行文件从终端运行,但不能从文件浏览器运行
- c# - 将 C# 加密转换为 PHP openssl 加密
- jquery - 点击图标触发jquery timepicker
- flutter - Flutter Searchable 下拉搜索问题
- c++ - 如何将带有双反斜杠的字符串转换为单反斜杠
- validation - 如何在 Orbeon 表单中设置特定的不对称约束