4.1直接发送请求
//1.安装依赖
yarn add axios
//2.直接在页面发送请求
//2.1导入axios
import axios from 'axios'
class App extends React.Component{
constructor(props){
super(props);
this.state={
songs:[]
}
}
//2.2发送请求
componentDidMount(){
var url='http://192.168.14.15:5000/search?keywords=海阔天空'
axios.get(url).then(res=>{
var songs=res.data.result.songs;
this.setState({
songs
})
})
}
//2.3渲染 使用map
render(){
{this.state.songs.map(item=>{
return (<div key={item.id}>
<p> {item.name}</p>
</div>)
)
}
4.2将axios挂载到原型上
//index.js中导入axios
import axios from 'axios'
//挂载到原型上
React.Component.prototype.$http=axios;
//App.js
componentDidMount(){
var url='http://192.168.14.15:5000/search?keywords=海阔天空'
this.$http.get(url).then(res=>{
var songs=res.data.result.songs;
this.setState({
songs
})
})
}