美文网首页
React学习日记

React学习日记

作者: DengXG | 来源:发表于2016-12-01 17:05 被阅读4次

es2015版本:

//需要 jquery库
class MyList extends React.Component {
    constructor(...args) {
      super(...args);
      this.state = {
        loading: true,
        error: null,
        data: null
      };
    }

    componentDidMount() {
      const url = 'https://api.github.com/search/repositories?q=javascript&sort=stars';
      $.getJSON(url)
       .done(
        (value) => this.setState({
          loading: false,
          data: value
        })
      ).fail(
        (jqXHR, textStatus) => this.setState({
          loading: false,
          error: jqXHR.status
        })
      );
    }

    render() {
      if (this.state.loading) {
        return <span>Loading...</span>;
      }
      else if (this.state.error !== null) {
        return <span>Error: {this.state.error}</span>;
      }
      else {
        /* 你的代码填入这里 */
        // console.log(this.state.data);
        let projects = this.state.data.items,
            result = [];
        projects.forEach(p => {
          let item = <li>{p.id}:{p.name}</li>;
          result.push(item);
        });
        return (
          <div>
            <p>API 数据获取成功</p>
            <p><ul>
              {result}
            </ul></p>
          </div>
        );
      }
    }
  };

  ReactDOM.render(
    <MyList/>,
    document.getElementById('example')
  );

相关文章

网友评论

      本文标题:React学习日记

      本文链接:https://www.haomeiwen.com/subject/ajoxmttx.html