import React from "react";
class App extends React.Component {
state = {
isLoading: true,
users: [],
error: null
};
fetchUers() {
fetch("https://randomuser.me/api/")
.then((response) => response.json())
.then((data) =>
this.setState({
users: data,
isLoading: false
})
)
.catch((error) => this.setState({ error, isLoading: false }));
}
componentDidMount() {
this.fetchUers();
}
render() {
const { isLoading, users, error } = this.state;
return (
<React.Fragment>
<h1> random user</h1>
{error ? <p> {error.message} </p> : null}
{isLoading ? (
users.map((user) => {
const { Image, title, first, last, Gender, address, cell } = user;
return (
<div key={username}>
<p>Image :{Image}</p>
<p>title :{title}</p>
<p>first :{first}</p>
<p>last :{last}</p>
<p>Gender :{Gender}</p>
<p>address :{address}</p>
<p>cell :{cell}</p>
<hr />
</div>
);
})
) : (
<h3> loading....</h3>
)}
</React.Fragment>
);
}
}
export default App;
试图从反应中获取数据,但无法获取数据,尝试从API获取图像,标题,第一,最后,性别,地址,单元格的
试图从反应中获取数据,但无法获取数据,尝试从API获取图像,标题,第一,最后,性别,地址,单元格的api 试图从react获取数据,但无法获取数据,尝试从API获取Image,title,first,last,Gender,address,cell的
答案 0 :(得分:0)
选项1:
fetchUers() {
const self = this;
fetch("https://randomuser.me/api/")
.then((response) => response.json())
.then((data) =>
self.setState({
users: data,
isLoading: false
})
)
.catch((error) => self.setState({ error, isLoading: false }));
}
选项2:
fetchUers() {
const handleSuccess = data => {
this.setState({
users: data,
isLoading: false
});
}.bind(this);
const handleError = error => {
this.setState({ error, isLoading: false });
}.bind(this);
fetch("https://randomuser.me/api/")
.then((response) => response.json())
.then(handleSuccess)
.catch(handleError);
}