4.1直接发送请求

  1. //1.安装依赖
  2. yarn add axios
  3. //2.直接在页面发送请求
  4. //2.1导入axios
  5. import axios from 'axios'
  6. class App extends React.Component{
  7. constructor(props){
  8. super(props);
  9. this.state={
  10. songs:[]
  11. }
  12. }
  13. //2.2发送请求
  14. componentDidMount(){
  15. var url='http://192.168.14.15:5000/search?keywords=海阔天空'
  16. axios.get(url).then(res=>{
  17. var songs=res.data.result.songs;
  18. this.setState({
  19. songs
  20. })
  21. })
  22. }
  23. //2.3渲染 使用map
  24. render(){
  25. {this.state.songs.map(item=>{
  26. return (<div key={item.id}>
  27. <p> {item.name}</p>
  28. </div>)
  29. )
  30. }

4.2将axios挂载到原型上

  1. //index.js中导入axios
  2. import axios from 'axios'
  3. //挂载到原型上
  4. React.Component.prototype.$http=axios;
  5. //App.js
  6. componentDidMount(){
  7. var url='http://192.168.14.15:5000/search?keywords=海阔天空'
  8. this.$http.get(url).then(res=>{
  9. var songs=res.data.result.songs;
  10. this.setState({
  11. songs
  12. })
  13. })
  14. }