4.1直接发送请求
//1.安装依赖yarn add axios//2.直接在页面发送请求//2.1导入axiosimport 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中导入axiosimport axios from 'axios'//挂载到原型上React.Component.prototype.$http=axios; //App.jscomponentDidMount(){ 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 }) }) }