1.react中使用ajax 需要使用第三方库 ,建议使用axiox
测试接口
2. npm 安装 axios
$npm install axios
代码中引入axios import axios from 'axios';
3.fetch请求的语法
4.案例
import React, {Component} from 'react'
import axios from 'axios'
export default class Test extends Component{
state={
name:'',
url:''
}
// 使用axios
componentDidMount(){
const url='https://api.github.com/search/repositories?q=topic:ruby+topic:rails'
// axios.get(url)
// .then(response => {
// console.log(response);
// console.log(response.data)
// const {url,name}=response.data.items[0]
// this.setState({
// name:name,
// url:url
// })
// })
// 使用fetch
fetch(url)
.then(response => {
return response.json()
})
.then(data => {
const {url,name}=data.items[0]
this.setState({
name:name,
url:url
})
})
}
render(){
const {name,url}=this.state
if(!name){
return <h3>loading ... </h3>
}else{
return (
<div>
<h3>start:</h3>
<a href={url}>{name}</a>
</div>
)
}
}
}