【发布时间】:2019-01-12 16:38:31
【问题描述】:
我正在尝试从要在表格中呈现的 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;
【问题讨论】:
-
this.setState({users: users})是异步的。这意味着当您尝试访问this.state时,您无法确定它是最新版本的 state。
标签: javascript reactjs api fetch