1、读取服务器上的数据
1-1、安装axios
npm i axios -S
yarn add axios
1-2、http请求挂载
//index.js
//axios挂载到原型上
import axios from 'axios';
React.Component.prototype.$http = axios;
1-3、在state中去定义变量装载从接口取得的数据
constructor(props) {
super(props);
this.state = {
musics: []
}
}
1-4 、ComponentDidMount发起http请求
//App.js
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
})
})
}
}
1-5、render函数中渲染数据
class App extends React.Component{
...
render() {
return (
<div>
{this.state.musics.map(item => {
return (<div key={item.id}>
<img src={item.coverImgUrl} alt={item.name} />
<p> {item.name}</p>
</div>)
})}
</div>
)
}
}