一、安装

  1. yarn add axios

二、直接请求

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

三、将axios挂载原型再请求

3-1 index.js配置

  1. //axios挂载到原型上
  2. import axios from 'axios';
  3. React.Component.prototype.$http = axios;

3-2请求数据

  1. componentDidMount(){
  2. var url = "https://music.aityp.com/top/playlist?cat=华语"
  3. this.$http.get(url).then(res=>{
  4. this.setState({
  5. musics:res.data.playlists
  6. })
  7. })
  8. }

3-3渲染数据

  1. //父组件
  2. render() {
  3. return (
  4. <div className="content">
  5. {this.state.musics.map((item,index)=>{
  6. return(
  7. <div key={index} onClick={this.handleDetail.bind(this,item.id)}>
  8. <MusicItem data={item} ></MusicItem>
  9. </div>
  10. )
  11. })}
  12. </div>
  13. );
  14. }
  15. //子组件
  16. render() {
  17. return (
  18. <div className="music-item">
  19. <img src={this.props.data.coverImgUrl} alt="" />
  20. <p>{this.props.data.name}</p>
  21. </div>
  22. );
  23. }