【发布时间】:2019-05-13 08:23:21
【问题描述】:
我有来自以下格式的 api 的 Json 响应
[
{
id: 1,
class: '10',
section: 'A',
subject: 'Social'
},
{
id: 2,
class: '8',
section: 'C',
subject: 'Social'
},
{
id: 3,
class: '9',
section: 'A',
subject: 'Social'
}
]
我将 json 响应存储在状态变量中,并且能够成功打印上述 json 数组。
async ListAllTodaysClasses() {
try {
let data = new FormData();
data.append('id', this.state.id)
data.append('year',this.state.year)
data.append('month',this.state.month)
data.append('day', this.state.day)
var url = this.state.url;
console.log(url);
let response = await fetch(url, {
method: 'POST',
body: data
});
let res = await response.json();
this.setState({
subjects: res
})
console.log(this.state.subjects)
} catch(error) {
this.setState({error: error});
console.log("error " + error);
}
}
这里我试图循环一个 json 响应数组。
this.state.subjects.map((item, key) => (
<TouchableOpacity key={key}>
<View>
{
<Text style={styles.textColor2}>{item.class}th-{item.section}/ {item.subject}</Text>
}
</View>
</TouchableOpacity>
))
但我收到 Typeerror: undefined is not a function
【问题讨论】:
-
“我将 json 响应存储在一个状态变量中……” 向我们展示这一点。如果您字面上将 JSON 响应存储为状态变量,则您存储的是字符串,而字符串没有
map。但希望您没有这样做,您正在解析 JSON 并存储结果,而不是 JSON。请记住,JSON 是一种用于数据交换的文本符号。 (More here.) 如果您正在处理 JavaScript 源代码,而不是处理 string,那么您就不是在处理 JSON。 -
你能发布你的完整组件吗?除非您展示如何获取 JSON 以及如何显示它,否则无法对此进行详细说明。请使用正确的代码更新您的帖子
-
我已经更新了代码@T.J.Crowder
-
我在代码中添加了api方法@AnkushRishi
标签: json react-native dictionary