2017-11-25 545 views
0

我想使用React從外部API顯示學校數據。我只是想顯示一個學校名稱開始。學校名稱出現在控制檯中,但不會顯示在瀏覽器中.API調用是正確的,因爲它在Postman中運行。這裏是我的代碼:React App:如何使用抓取顯示來自api的數據

import React, { Component } from 'react'; 
import './App.css'; 

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     schoolName: '', 
     // schoolData: {} 
    } 
    } 

    fetchSchool(event) { 
    event.preventDefault(); 

    const apiKey = 'XdOHSc8fKhMKidPu2HWqCZmMy9OxtCJamGC580Bi'; 
    const fields = `_fields=school.name,2015.aid.median_debt.completers.overall,2015.cost.tuition.in_state&school.name=${this.state.schoolName}`; 
    const requestUrl = `https://api.data.gov/ed/collegescorecard/v1/schools?&api_key=${apiKey}&${fields}`; 

    const school = fetch(requestUrl).then((res) => res.json()).then((data) => console.log(data.results[0]['school.name'])); 

    this.setState({ 
     schoolName: school 
     // schoolData: school 
    }) 
    console.log(this.state.schoolName); 
    } 

    setSchool(event) { 
    event.preventDefault(); 
    this.setState({ 
     schoolName: event.target.value 
    }); 
    } 

    render() { 
    // const schoolname = this.state.schoolName[0]; 
    // const {schooName} = this.state; 
    return (
     <div> 
     <form action="/school" method="GET" id="myform"> 
      <input type="text" className="form-control" id="enter_text" onChange={this.setSchool.bind(this)} /> 
      <button onClick={this.fetchSchool.bind(this)} type="submit" className="btn btn-primary" id="text-enter-button button submit">Submit</button> 
     </form> 
     <div> 
     <p>School: {this.state.school} </p> 
     </div> 
     </div> 
    ); 
    } 
} 

export default App; 
+0

我建議刪除值apiKey如果是敏感的信息,請撥打this.setState。 – Kunukn

回答

0

在渲染處理方法改變這一行,因爲schoolName是你的狀態變量,而不是school

<p>School: {this.state.school} </p> 

<p>School: {this.state.schoolName} </p> 
1

fetch是異步的。因此,在獲取數據之前調用setState

要解決這個問題,從您的then函數內

const school = fetch(requestUrl) 
    .then((res) => res.json()) 
    .then((data) => { 
    console.log(data.results[0]['school.name']) 
    this.setState({ 
     schoolName: data.results[0]['school.name'], 
     schoolData: data.results 
    }) 
    }); 
+0

謝謝!這工作...差不多。學校名稱顯示在瀏覽器中,但顯示爲我輸入,而不是在點擊「提交」之後。 – user8767190

+0

從'input'元素中刪除'onChange = {this.setSchool.bind(this)}' –

+0

這給了我一個新的錯誤:無法讀取未定義的'school.name'的屬性(在獲取請求中) – user8767190