簡體   English   中英

如何使用從Reactjs中的fetch()獲得的JSON數據填充引導網格?

[英]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但顯示錯誤,請參見下面的屏幕截圖。

在此處輸入圖片說明

只需等待setState()被調用,這將依次填充matches數組。 請記住,因為您使用的是componentDidMount ,並且進行了異步調用以獲取數據,所以該組件將已經使用this.state.matches設置為空數組進行渲染。

這是一個快速的CodePen

這也可能有幫助- 在哪里獲取數據

我們可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM