1、读取服务器上的数据

1-1、安装axios

  1. npm i axios -S
  2. yarn add axios

1-2、http请求挂载

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

1-3、在state中去定义变量装载从接口取得的数据

  1. constructor(props) {
  2. super(props);
  3. this.state = {
  4. musics: []
  5. }
  6. }

1-4 、ComponentDidMount发起http请求

  1. //App.js
  2. import axios from 'axios'
  3. class App extends React.Component{
  4. ....
  5. componentDidMount() {
  6. var url = "http://192.168.14.49:5000/top/playlist?cat=华语"
  7. axios.get(url).then(res => {
  8. console.log(res.data.playlists)
  9. this.setState({
  10. musics: res.data.playlists
  11. })
  12. })
  13. }
  14. }

1-5、render函数中渲染数据

  1. class App extends React.Component{
  2. ...
  3. render() {
  4. return (
  5. <div>
  6. {this.state.musics.map(item => {
  7. return (<div key={item.id}>
  8. <img src={item.coverImgUrl} alt={item.name} />
  9. <p> {item.name}</p>
  10. </div>)
  11. })}
  12. </div>
  13. )
  14. }
  15. }