状态正在改变,但数据表未显示新数据

State is changing but datatable not showing new data

我正在使用 material-ui 库并制作数据table。对于数据table,我正在使用这个库mui-datatables。我需要调用 API 来检索数据并显示在 table 中。我在控制台中检查数据即将到来但未显示在数据 table.

下面是我的代码:

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>

如果有人能帮帮我就好了。

您直接改变状态以更新 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 });
    });
  }

来自 React docs:

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state.

state 也可以像上面那样直接变异。但这不会触发重新渲染。因此,如果您需要显示新数据,请始终使用 setState 更新状态。