我正在尝试显示此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 {
}
答案 0 :(得分:0)
我可以在地图函数上传递参数i
的方式上看到错误,请看一下如何使用map来渲染<li>
元素的简单示例。
var dataSample = [
{ "id": "1", "imagename": "dog" },
{ "id": "2", "imagename": "cat" },
{ "id": "3", "imagename": "mouse" },
{ "id": "4", "imagename": "deer" },
{ "id": "5", "imagename": "shark" },
{ "id": "6", "imagename": "ant" }
];
const App = () => (
<div>
<ul>
{dataSample.map((data, i) => {
return <li key={i}>{i + ' - ' + data.imagename}</li>
})}
</ul>
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>