从JSON获取URL并显示数据

时间:2017-03-03 00:47:04

标签: javascript json reactjs

我有一个网络应用程序,您可以在其中按名称搜索存储库。它显示一些信息但我想显示自述文件,如果repo有一个。我知道我需要单独取出它,但我不能100%确定如何做到这一点。如何获取它并将其显示为另一个列表对象。

这是没有自述文件的工作代码。



let searchTerm;

class SearchBox extends React.Component {


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

  }


  render() {
    const moreDetail = (item) => (!this.state.showInfo ? < span / > :
      <
      div className = "info" >
      <
      li >
      <
      p > Open issue count: {
        item.open_issues_count
      } < /p> <
      /li> <
      li >
      <
      p > Number of forks: {
        item.forks
      } < /p> <
      /li> <
      li >
      <
      p > Language: {
        item.language
      } < /p> <
      /li> <
      /div>
    );

    return ( <
      div >
      <
      form >
      <
      input type = "text"
      className = "searchbox"
      ref = {
        (input) => {
          this.searchBox = input;
        }
      }
      /> <
      button onClick = {
        this.onClick
      } > Search < /button> <
      /form> <
      div className = "results" >
      <
      h2 > Repositories < /h2> <
      button onClick = {
        this._handleClick.bind(this)
      } > Detailed view < /button> <
      /div> <
      ul > {
        this.state.repositories.map((item, index) => ( <
          div className = "repository"
          key = {
            index
          } >
          <
          a href = {
            item.html_url
          } > < li className = "repoName" > {
            item.name
          }

          <
          /li> <
          /a> {
            moreDetail(item)
          }


          <
          /div>
        ))
      } <
      /ul>

      <
      /div>
    );
  }

  _handleClick() {
    this.setState({
      showInfo: !this.state.showInfo
    });
  }


  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();

  }
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;

我正在使用Github搜索API制作一个webapp。搜索存储库时,它应显示存储库及其相关信息,包括自述文件。 到目前为止,除了显示自述文件外,它还能做到这一切。

0 个答案:

没有答案
相关问题