import React from 'react';
import axios from 'axios'
class Axios extends React.Component {
//构造函数
constructor() {
super();
//react定义数据
this.state = {
list:[]
}
}
//请求接口的方法
getData=()=>{
var api='https://www.apiopen.top/weatherApi?city=%E4%B8%8A%E6%B5%B7';
axios.get(api)
.then((response) =>{
//console.log(response);
console.log(response.data.data.yesterday);
//用到this需要注意指向,箭头函数
this.setState({
list:response.data.data.forecast
})
})
.catch(function (error) {
// handle error
console.log(error);
});
}
render() {
return (
<div>
<h2>axios获取数据</h2>
<button onClick={this.getData}>获取api接口</button>
<ul>
{/* 对数组进行循环 */}
{
this.state.list.map((value,key)=>{
return<li key={key}>{value.date}</li>
})
}
</ul>
</div>
)
}
}
export default Axios;