我正在学习 ReactJS。在我的程序中,我进行了 API 调用,然后进行了映射。API调用获取的数据是这样的, data = [{"uid":"1", "title":"hello"},{"uid":"2", "title":"World"}]
import ImporterAPI from '../api';
const API = new ImporterAPI();
class Home extends Component {
constructor(props) {
super(props);
this.state = {
data: ''
}}
componentWillMount() {
this.setState({ data: API.getData()}, () => {
console.log("data fetched");
var mapData = []
this.state.data.map( (object, i) => {
mapData.push(<p key={i}>{object}</p>)
})
})
}
render() {
return (
<div className="home">
{this.mapData}
</div>
)
}
}
还有我的 API 文件,
import axios from 'axios';
class API {
getData = () => {
axios.get('http://localhost:8005/data')
.then(function (response) {
if (response.status === 200 && response != null) {
var data = response.data;
console.log(data)
return data
} else {
console.log('problem');
}
})
.catch(function (error) {
console.log(error);
});
}
}
我的 console.log 正在打印来自 API 调用的数据,然后我正在返回数据。使用 setState 分配家庭组件数据的位置。但是没有数据存储到 this.state.data 中。它始终保持未定义状态,并且出现错误“TypeError:无法读取未定义的属性‘地图’”。
请指导我。我应该如何打印 API 调用数据 & 我还想知道这个程序在进行 API 调用的性能方面是好是坏,或者是任何其他更好的提高性能的方法。谢谢。
我将不胜感激。