2017-03-02 6 views
-1

Githubからリポジトリを検索するためにSearch APIを使用しています。私は現在reposを検索することができますが、私はrepoの名前とページ上の情報を表示したいと思います。私はReactでページを構築しています。 JSONファイルからデータを取得してページ自体に追加するにはどうすればよいですか?リポジトリの表示名Github Search API from React

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

関連する問題