我想将 JSON 数据填充到 Bootstrap 网格系统中。 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 响应返回大约 577 个 JSON 对象,现在我想将上述 JSON 数据填充到 Bootstrap 网格系统中。
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
匹配[8].season
,但显示错误,请参见下面的屏幕截图。
最佳答案
只需等待 setState()
被调用,这将依次填充 matches
数组。请记住,由于您使用的是 componentDidMount
,并且进行异步调用来获取数据,因此该组件已使用 this.state.matches< 进行渲染
设置为空数组。
这是一个快速CodePen .
这也可能有帮助 - Where to Fetch Data
关于javascript - 如何使用 Reactjs 中的 fetch() 获取的 JSON 数据填充 Bootstrap 网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48384411/