一、创建react-app

  1. # npm install -g create-react-app
  1. npx create-react-app my-app
  2. cd my-app
  3. npm start

二、删除src下多余的文件-启动hello world

  1. src
  2. index.js
  3. App.js
  4. //index.js
  5. import React from 'react';
  6. import ReactDOM from 'react-dom';
  7. import App from './App';
  8. ReactDOM.render(<App />, document.getElementById('root'));
  9. //App.js
  10. import React from 'react';
  11. class App extends React.Component{
  12. render(){
  13. return (<div>hello world</div>)
  14. }
  15. }

三、读取服务器上的数据

3-1 安装axios

  1. npm i axios -S

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

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

3-3 ComponentDidMount发起http请求

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

3-4 render函数中渲染数据

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