请帮助我
我只是了解ReactJs,现在我了解了有关从Api获取数据的信息,在此之前,我使用fetch获取api并使其正常,但是当我使用Axios并遇到该问题时
import React, { Component } from 'react';
import './App.css';
import Axios from 'axios'
class App extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
Axios({
method: "GET",
url: "https://reqres.in/api/users"
}).then(res => {
this.setState({
isLoaded: true,
items: res.data
})
console.log(res.data)
}).catch(err => {
console.log(err)
})
}
render() {
const { error, isLoaded, items = [] } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
{items.map(function (item, i) {
return <div key={i}>
<p>{item.id}</p>
<img src={item.avatar} alt="Card" />
</div>
})}
</div>
);
}
}
}
export default App;
这是要求的数据
{"page":1,"per_page":3,"total":12,"total_pages":4,"data":
[ {"id":1,"first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"},
{"id":2,"first_name":"Janet","last_name":"Weaver","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"},
{"id":3,"first_name":"Emma","last_name":"Wong","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"}
]}
这是来自反应的错误
我只想显示我的数据:(
答案 0 :(得分:0)
看起来res.data不是您可以遍历的内容。尝试检查里面有什么
编辑:
从输出中可以看到:
{"page":1,"per_page":3,"total":12,"total_pages":4,"data":
[ {"id":1,"first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"},
{"id":2,"first_name":"Janet","last_name":"Weaver","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"},
{"id":3,"first_name":"Emma","last_name":"Wong","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"}
]}
您的信息位于data属性内部,因此,只需对其进行循环:
{items.data.map(function (item, i) {
return <div key={i}>
<p>{item.id}</p>
<img src={item.avatar} alt="Card" />
</div>
})}
答案 1 :(得分:0)
查看API响应,声明应为
items: res.data.data