【发布时间】:2018-10-30 15:18:48
【问题描述】:
我正在尝试显示此 JSON 数据:
[
{
"id":"1",
"imagename":"dog"
},
{
"id":"2",
"imagename":"cat"
},
{
"id":"3",
"imagename":"mouse"
},
{
"id":"4",
"imagename":"deer"
},
{
"id":"5",
"imagename":"shark"
},
{
"id":"6",
"imagename":"ant"
}
]
这是我必须显示该数据的当前代码:
componentDidMount(){
fetch(`http://www.example.com/React/data.php`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((responseJson) => {
this.data = responseJson;
this.setState({ loading: false });
}).catch((error) => {
console.warn(error);
});
}
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View>
<Text>{this.data.id}</Text>
<Text>{this.data.imagename}</Text>
</View>
</Card>
</View>
</View>
);
我的结果是什么都没有显示,但是当我只有 this.data 时,我再次得到带有键的对象错误。
查找类似的答案以找到我的问题,然后我尝试.map,但我不断收到cannot not find variable: i:
this.data = responseJson.map(item => ({ ...item, i }))
最后,这是我尝试的其余代码:
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View key={i}>
<Text>{item.id}</Text>
<Text>{item.imagename}</Text>
</View>
</Card>
</View>
</View>
);
当我将我的 json 数据放入一个数组时,什么都没有显示,因为(我猜)键之间没有逗号。像这样:
{"id":"1","imagename":"dog"}{"id":"2","imagename":"cat"}{"id":"3","imagename":"mouse"}{"id":"4","imagename":"deer"}{"id":"5","imagename":"shark"}{"id":"6","imagename":"ant"}
如果有人需要查看我的data.php:
回声对象
$dsql = "SELECT * FROM random";
$dresult = $con->query($dsql);
if ($dresult->num_rows >0) {
while($drow[] = $dresult->fetch_assoc()) {
$dtem = $drow;
$djson = json_encode($dtem);
}
} else {
}
echo $djson;
回声阵列
$dsql = "SELECT * FROM random";
$dresult = $con->query($dsql);
if ($dresult->num_rows >0) {
while($drow = $dresult->fetch_assoc()) {
$dtem = $drow;
$djson = json_encode($dtem);
echo $djson;
}
} else {
}
【问题讨论】:
-
你必须定义索引(i变量)作为map函数的第二个参数,尝试改为:
this.data = responseJson.map((item, i) => ({ //... More logic here })) -
@ricardoorellana 嗯,我得到了这个:
ReferenceError: Can't find variable: i我也试过这样做:i: responseJson,但我仍然得到错误。
标签: arrays json reactjs object react-native