import React,{ Component } from 'react';
export class FetchData extends Component {
static displayName = FetchData.name;
constructor(props) {
super(props);
this.state = { users: [],loading: true };
}
componentDidmount() {
this.populateUserData();
}
static renderUsersTable(users) {
return (
<table classname='table table-striped' aria-labelledby="tabelLabel">
<thead>
<tr>
<th>username</th>
<th>Likes</th>
<th>Image Url</th>
</tr>
</thead>
<tbody>
{users.map(id =>
<tr key={id.user}>
<td>{id.username}</td>
<td>{id.likes}</td>
<td>{id.imageUrl}</td>
</tr>
)}
</tbody>
</table>
);
}
render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: FetchData.renderUsersTable(this.state.users);
return (
<div>
<h1 id="tabelLabel" >API info</h1>
<p>This component demonstrates fetching data from the api.</p>
{contents}
</div>
);
}
async populateUserData() {
const response = await fetch('http://api.myjson.com/bins/1ge417');
const data = await response.json();
this.setState({ users: data,loading: false });
}
}
为什么我的JavaScript代码没有从JSON API返回任何数据?我指定了一个Array类型,它仍然不返回任何东西。任何帮助/更正将不胜感激!
P.S。这是我从“ dotnet new react -o my-new-app”中使用的模板