我需要一些帮助,在jsx里面的json中呈现json in react native ..我从服务器获取的响应是对象所以我如何循环它们?我从服务器获得了有效的响应,但是我在地图方法上遇到问题,因为我认为地图方法只适用于数组。所以请帮我做这个。以下是json对象
JSON
{
"content": "<p><strong>Preliminary Exam; MCQ –1</strong></p>\n",
"meta": {
"access": 1,
"status": 0,
"progress": 0,
"marks": 0,
"max": 60,
"questions": [
{
"type": "single",
"hint": "",
"explanation": "",
"content": "<p>Question Statement :</p>\n<ol>\n<li>The is question:</li>\n</ol>\n",
"options": [
"(a).Answer1",
"(b).Answer2 ",
"(c).Answer3 ",
"(d).Answer4 "
],
"correct": "4",
"marks": 4,
"user_marks": 0,
"status": 0,
"marked": null,
"auto": 1
},
{
"type": "single",
"hint": "",
"explanation": "",
"content": "<p>2.Question 2</p>\n",
"options": [
"(a) one ",
"(b) two ",
"(c) three ",
"(d) four"
],
"correct": "2",
"marks": 4,
"user_marks": 0,
"status": 0,
"marked": null,
"auto": 1
}
]
}
}
我尝试过以下
examplecode
state = { details: [] };
componentWillMount() {
AsyncStorage.getItem('userdetail').then((value) => {
console.log(value);
fetch('https://www.mywebsite.com', {
method:'GET',
headers: {
'Authorization': value
}
})
.then((response) => response.json())
.then((responseData) =>
this.setState({
details:responseData.meta.questions
})
);
});
}
render() {
console.log(this.state);
return (
this.state.details.map( a =>
<Card>
<CardSection>
<Text>{a.questions.content}</Text>
</CardSection>
</Card>
);
}
但是获得错误this.state.details.map
不是一个功能?我的渲染方法有问题吗?请帮忙。
答案 0 :(得分:1)
问题在于responseData
,它是一个对象而不是数组,请尝试使用
details:responseData.meta.questions
答案 1 :(得分:0)
map方法/函数的问题在于你是在单个对象而不是数组中使用它。您的responseData
是一个巨大的对象,其中包含questions
数组。您可以按如下方式映射问题:
render() {
console.log(this.state);
return (
this.state.details.meta.questions.map( a =>
<Card>
<CardSection>
<Text>{a.content}</Text>
</CardSection>
</Card>
);
);
}
这应该可以解决您的问题