1. 安装
npm isntall axios --save
2. 使用
import React, { Component } from 'react';
import axios from 'axios';
class App extends Component {
state = {
repoName: '',
repoUrl: ''
}
// 页面渲染完成执行异步操作
componentDidMount(){
const url = 'https://api.github.com/search/repositories?q=r&sort=stars'
axios.get(url).then(result=>{
const {name, html_url} = result.data.items[0];
this.setState({
repoName: name,
repoUrl: html_url
})
})
}
render() {
const {repoName, repoUrl} = this.state;
if(!repoName){
return(
<h2> loading... </h2>
)
}else{
return(
<h2> 最受欢迎的仓库是 <a href={repoUrl}> {repoName} </a> </h2>
)
}
}
}
export default App;