[英]How to populate bootstrap grids with JSON data obtained from fetch() in Reactjs?
我想將JSON數據填充到引導網格系統中。 JSON響應:
{
"_id": "5a63051735aaddd30d1d89f8",
"id": 45,
"season": 2008,
"city": "Bangalore",
"team1": "Royal Challengers Bangalore",
"team2": "Delhi Daredevils",
"toss_winner": "Delhi Daredevils",
"toss_decision": "field",
"result": "normal",
"dl_applied": 0,
"winner": "Delhi Daredevils",
"win_by_runs": 0,
"win_by_wickets": 5,
"player_of_match": "SP Goswami",
"venue": "M Chinnaswamy Stadium",
"umpire1": "SJ Davis",
"umpire2": "GA Pratapkumar",
"umpire3": ""
}
現在,我想將JSON數據上方的JSON數據填充到引導網格系統中,JSON響應返回大約577個JSON對象。
main.js
class Main extends Component {
constructor(){
super();
this.state={
matches: []
};
}
componentDidMount(){
fetch('api/matches')
.then(res => res.json())
.then(matches => this.setState({matches}, () => console.log('Matches fetched...', matches)));
}
render() {
return (
<div>
<div class="row">
<div class="col-lg-4" styles="background-color:lavender;">{this.state.matches[0].season}</div>
<div class="col-lg-4" styles="background-color:lavenderblush;">{this.state.matches[5].season}</div>
<div class="col-lg-4" styles="background-color:lavender;">{this.state.matches[8].season}</div>
</div>
</div>
);
}
}
在上面的代碼中,我試圖顯示matches[0].season
matches[5].season
matches[8].season
但顯示錯誤,請參見下面的屏幕截圖。
我們可以使用fetch()
填充引導程序網格,請參見以下代碼:
componentDidMount() {
fetch('api/matches')
.then(res => res.json()) // It resolves the promise with a JSON object
.then(res => {
console.log(res)
this.setState({
matches: res,
})
})
}
同樣在render函數中添加條件語句:
render() {
if (this.state.matches.length === 0) {
return <div>>Loading...</div>
}
return (
<div>
<div class="row">
<div class="col-lg-4" styles="background-color:lavender;">{this.state.matches[0].season}</div>
<div class="col-lg-4" styles="background-color:lavenderblush;">{this.state.matches[5].season}</div>
<div class="col-lg-4" styles="background-color:lavender;">{this.state.matches[8].season}</div>
</div>
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.