一、创建react-app
# npm install -g create-react-app
npx create-react-app my-appcd my-appnpm start
二、删除src下多余的文件-启动hello world
src index.js App.js//index.jsimport React from 'react';import ReactDOM from 'react-dom';import App from './App';ReactDOM.render(<App />, document.getElementById('root'));//App.jsimport React from 'react';class App extends React.Component{ render(){ return (<div>hello world</div>) }}
三、读取服务器上的数据
3-1 安装axios
npm i axios -S
3-2 在state中去定义变量装载从接口取得的数据
constructor(props) { super(props); this.state = { musics: [] } }
3-3 ComponentDidMount发起http请求
import axios from 'axios'class App extends React.Component{ .... componentDidMount() { var url = "http://192.168.14.49:5000/top/playlist?cat=华语" axios.get(url).then(res => { console.log(res.data.playlists) this.setState({ musics: res.data.playlists }) }) }}
3-4 render函数中渲染数据
class App extends React.Component{ ... render() { return ( <div> <div> {this.state.musics.map(item => { return (<div key={item.id}> <img src={item.coverImgUrl} alt={item.name} /> <p> {item.name}</p> </div>) })} </div> </div> ) }}