如何使用从Reactjs中的fetch()获取的JSON数据填充bootstrap网格?

时间:2018-01-22 14:57:27

标签: javascript json twitter-bootstrap reactjs

我想将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数据填充到引导网格系统中。

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但显示错误,请参见下方的截图。

enter image description here

2 个答案:

答案 0 :(得分:1)

只需要等待setState()被调用,这反过来会填充matches数组。请记住,因为您正在使用componentDidMount,以及对获取数据进行异步调用,所以该组件已经将this.state.matches设置为空数组。< / p>

这是一个快速CodePen

这也有帮助 - Where to Fetch Data

答案 1 :(得分:0)

我们可以使用fetch()填充bootstrap网格,请参阅下面的代码:

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() {
  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>
  )
}