我爱编程

React中的“ajax”

2018-05-23  本文已影响0人  zhangjingbibibi

下面记录一个小例子:

  class UserGist extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        lastGistUrl: null
      };
    }

    componentDidMount() {
      const url = `https://api.github.com/users/${this.props.name}/gists`
      axios.get(url)
          .then((response) => {
            console.log(response.data)
            var data = response.data;

            var lastGist = data[0];
            this.setState({
              lastGistUrl: lastGist.html_url
            });
          })
          .catch((error) => {
            console.log(error.response.data);
          });

      /*fetch(url).then(
          (response) => {
            response.json().then((result) => {
              console.log(result);
              var lastGist = result[0];
              this.setState({
                lastGistUrl: lastGist.html_url
              });
            })
          },
          (error) => {
            console.log(error);
          }
      );*/
    }

    render() {
      if(this.state.lastGistUrl===null) {
        return <h2>loading...</h2>
      } else {
        return (
            <div>
              {this.props.name}'s last gist is <a href={this.state.lastGistUrl}>here</a>
            </div>
        );
      }
    }
  }

  var name = 'octocat'
  ReactDOM.render(<UserGist name={name}/>, document.getElementById('example'));

这里可以提一点:axios跟fetch的异同。

说的这里就联想到同源策略已经跨域安全方面的事情。

上一篇 下一篇

猜你喜欢

热点阅读