2017-03-02 108 views
-1

我正在使用Search API從Github中查找存儲庫。我目前能夠搜索回購站,但我想在頁面上顯示回購站的名稱和信息。我正在React中構建頁面。如何從JSON文件獲取數據並將其添加到頁面本身?顯示Github中存儲庫的名稱React中的搜索API

let searchTerm; 
const repositories = []; 

class SearchBox extends React.Component { 

    constructor(props) { 
     super(props); 
     this.onClick = this.onClick.bind(this); 

    } 


    render() { 
     return(
     <div> 
      <form> 
       <input type="text" className="searchbox" ref={(input) => { this.searchBox = input; }}/> 
       <button onClick={this.onClick}>Search</button> 
      </form> 
      <div className="foundRepo">{this.props.name}</div> 
      </div> 
     ); 
    } 

    onClick(event) { 

    searchTerm = this.searchBox.value; 
    let endpoint = 'https://api.github.com/search/repositories?sort=stars&order=desc&q=' + searchTerm; 
    console.log(searchTerm); 
     fetch(endpoint) 
    .then(blob => blob.json()) 
    .then(data => repositories.push(...data)); 
    event.preventDefault(); 


    } 
} 

這兩個反應和使用API​​對我來說都是很新的,所以代碼可能有點混亂,但它確實有效。只需要一些關於如何訪問數據的幫助。謝謝。

+0

的回答將是巨大的,但我也真的很感激的解釋或鏈接到好的解釋,所以我能理解我做什麼:) – Naomi

回答

0

將響應數據存儲在組件狀態中,並使用.map循環顯示它。您應該閱讀有關how component state works

let searchTerm; 

class SearchBox extends React.Component { 

    constructor(props) { 
     super(props); 
     this.onClick = this.onClick.bind(this); 
     this.state = { repositories: [] }; 
    } 


    render() { 
     return(
      <div> 
       <form> 
       <input type="text" className="searchbox" ref={(input) => { this.searchBox = input; }}/> 
       <button onClick={this.onClick}>Search</button> 
       </form> 
       <div className="foundRepo">{this.props.name}</div> 
       <h2>Repositories</h2> 
       <ul> 
       { this.state.repositories.map((item, index) => (
        <li key={ index }> 
         { item.name } 
        </li> 
       )) } 
       </ul> 
      </div> 
      ); 
    } 

    onClick(event) { 

     searchTerm = this.searchBox.value; 
     let endpoint = 'https://api.github.com/search/repositories?sort=stars&order=desc&q=' + searchTerm; 
     console.log(searchTerm); 
     fetch(endpoint) 
      .then(blob => blob.json()) 
      .then(response => { 
       this.setState({ repositories: response.items }); 
      }); 
     event.preventDefault(); 

    } 
} 
+0

我在控制檯中的錯誤信息,說無法讀取屬性「地圖」的未定義。 – Naomi

+0

更新了答案。 –

+0

謝謝!你是一個救星! – Naomi