![](/img/trans.png)
[英]How to display / render data from fetched api with the help of async await
[英]How to render fetched data from API
我正在嘗試從要在表中呈現的API提取數據。 我正在關注此示例,並且還嘗試了其他示例: https : //blog.hellojs.org/fetching-api-data-with-react-js-460fe8bbf8f2
當我嘗試console.log時,我得到的狀態是不確定的。 當我console.log數據時,我會收到正確的數據。 我知道如何使用純JavaScript解決我的問題,但我確實想使它以這種方式工作。
import React from "react";
import Row from '../components/Row';
class Table extends React.Component {
constructor() {
super();
this.state = {
users: [],
};
this.createNewUser = this.createNewUser.bind(this);
this.deleteExistingUser = this.deleteExistingUser.bind(this);
}
componentDidMount() {
console.log("Component did mount!");
fetch("http://localhost:8080/users")
.then(response => {
return response.json();
}).then(data => {
let users = data.response.map((row) => {
return (
<tr>
<td>{row.name}</td>
<td>{row.email}</td>
<td>{row.phone}</td>
<td>{row.age}</td>
<td>
<button className="red waves-effect waves-light btn">
Delete
</button>
</td>
</tr>
);
});
this.setState({users: users});
console.log("state", this.state.users);
});
}
render() {
return (
<table id="" className="highlight centered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Age</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="table_body">
{this.state.users}
</tbody>
</table>
);
}
}
export default Table;
Okey,所以經過一番修補,我能夠解決它。
我從:
let users = data.response.map((row) => {
return (
<tr>
<td>{row.name}</td>
<td>{row.email}</td>
<td>{row.phone}</td>
<td>{row.age}</td>
<td>
<button className="red waves-effect waves-light btn">
Delete
</button>
</td>
</tr>
);
});
至:
let users = data.map((row) => {
return <Row key={row.email} name={row.name} email={row.email}
phone={row.phone} age={row.age}/>
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.