我正在学习做出反应,偶然发现了一个似乎完全是初学者的问题。无论如何,我正在从API获取数据,并且想知道如何从JSON获取特定元素。我用[0]尝试了其他变体,但没有成功。
这是.json:
{
"data": [
{
"id": 68,
"name": "Umrah bersama Da'i Hadhari",
"duration": "12D10N",
"slug": "umrah-bersama-dai-hadhari-november-disember",
"type": "umrah",
"isPublished": true,
"isHighlighted": true,
"promoStatus": null,
"tourCode": null,
"displayName": "Umrah bersama Da'i Hadhari",
},
{
"id": 70,
"name": "Umrah bersama Da'i Fuad",
"duration": "12D10N",
"slug": "umrah-bersama-dai-fuad-2018",
"type": "umrah",
"isPublished": true,
"isHighlighted": true,
"promoStatus": null,
"tourCode": "UGOCT18-ECON",
"displayName": "Umrah bersama Da'i Fuad",
},
{
"id": 45,
"name": "Umrah Super Ekonomi - Disember",
"duration": "12D10N",
"slug": "ugdec18-umrah-disember-cuti-sekolah",
"type": "umrah",
"isPublished": true,
"isHighlighted": true,
"promoStatus": null,
"tourCode": "UGOCT18 - P/FB",
"displayName": "Umrah Super Ekonomi - Disember",
},
{
"id": 47,
"name": "Umrah Super Ekonomi - November",
"duration": "12D10N",
"slug": "ugnov18-p-fb-umrah-november-cuti-sekolah-musim-sejuk",
"type": "umrah",
"isPublished": true,
"isHighlighted": true,
"promoStatus": null,
"tourCode": "UGNOV18 - S.ECON",
"displayName": "Umrah Super Ekonomi - November",
},
]
}
这是我的代码:
class PackageDetails extends React.Component {
constructor (props) {
super (props);
this.state = {
data: [],
}
}
componentDidMount () {
fetch ('http://localhost/sampleData.json')
.then ((Response) => Response.json())
.then ((findresponse) => {
console.log(findresponse.data[0])
this.setState({
data:findresponse.data[0],
})
})
}
render () {
return (
<div>
<Navigation/>
<Breedcrumbs/>
<section className="section-highlight">
<div className="container">
{
this.state.data.map((dynamicData,i) =>
<ContentHighlight
name={dynamicData.name}
packageType={dynamicData.packageType}
highlight={dynamicData.highlight}
/>
)
}
</div>
</section>
</div>
)
}
}
export default PackageDetails;
我只想访问第一组数据。它可以在console.log上运行,但不能在this.setState上运行。
请帮助我。谢谢