一、创建react-app
使用以下方法创建
npx create-react-app my-app
//cd my-app 暂定
npm start
二、删除src下多余的文件-启动hello world
//src下面只留以下文件
index.js
App.js
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
//App.js
import React from 'react';
class App extends React.Component{
render(){
return (<div>hello world</div>)
}
}
新建文件夹views/Home
将app.js移入Home,并改名为index.js
更改index.js中的Home/index.js的路径
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './pages/App/App';
ReactDOM.render(<App />, document.getElementById('root'));
三、读取服务器上的数据
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>
)
}
}