我正在尝试在表FORNMAT中显示数据。数据来自API。我需要显示表一旦数据接收从api。我正在使用类组件。下面我给出了尝试的东西。
//下面是我的jsx
<div>
<input onChange={this.handleSearchChange} placeholder="Search" />
<div>
if (!this.state.user.length) return <div>No data</div>
<table>
<thead>
<th>Color</th>
<th>Name</th>
<th>Age</th>
</thead>
<tbody> </tbody>
</table>
</div>
</div>
//下面是我从api获取数据的函数
handleSearchChange = (e) => {
const { value } = e.target;
var self = this;
axios
.post("http://localhost:3000/user", { namr: value })
.then(function (res) {
this.setState({ user: res.data });
})
.catch(function (err) {
console.log("Error", err);
});
};
//下面是我的api输出
[
{color: "green",name: "test",age: "22"},
{color: "red",name: "test2",age: "23"}
]
您可以在数据进入HTML元素时进行迭代:
<table>
<thead>
<th>Color</th>
<th>Name</th>
<th>Age</th>
</thead>
<tbody>
{user.map(userData => (
// A unique key for each element
<tr key={userData.name}>
<td>{userData.name}</td>
<td>{userData.color}</td>
<td>{userData.age}</td>
</tr>
))}
</tbody>
</table>;