我正在使用资料-ui库并制作数据。对于datatable,我使用的是这个库梅氏数据。我需要调用一个API来检索数据并显示在表中。我在控制台中签入了数据,但没有显示在datatable中。
下面是我的代码:
state = {
students: [],
rows: []
};
componentDidMount() {
document.title = "List of students";
axios
.get("api.url")
.then(res => {
this.setState({ students: res.data }, () => {
this.state.students.forEach((value, index) => {
this.state.rows.push({
digitalcredid: value.studentid,
firstname: value.firstname,
lastname: value.lastname,
email: value.email,
nationality: value.nationality,
postaladress: value.postaladress,
nic: value.nic
});
});
});
});
}
并显示如下数据:
const options = {
filterType: "checkbox",
serverSide: true,
print: false
};
<div className="row">
<div className="col-12">
<MUIDataTable
title={"Student List"}
data={this.state.rows}
columns={studentColumns}
options={options}
/>
</div>
</div>
如果有人能帮我的话那就太好了。
发布于 2019-11-02 08:09:30
您正在直接更改状态以更新rows
,而不是调用setState
,因此不会触发重呈现。试试这个:
componentDidMount() {
document.title = "List of students";
axios.get("api.url").then(res => {
const rows = [];
res.data.forEach((value, index) => {
rows.push({
digitalcredid: value.studentid,
firstname: value.firstname,
lastname: value.lastname,
email: value.email,
nationality: value.nationality,
postaladress: value.postaladress,
nic: value.nic
});
});
this.setState({ students: res.data, rows });
});
}
从反应文档
setState()将更改到组件状态,并告诉React该组件及其子组件需要用更新的状态重新呈现。
state
也可以像上面那样直接变异。但这不会触发重渲染。因此,如果需要显示新的数据,请始终使用setState
更新状态。
https://stackoverflow.com/questions/58669265
复制相似问题