【问题标题】:State is changing but datatable not showing new data状态正在改变,但数据表未显示新数据
【发布时间】:2020-02-28 08:14:19
【问题描述】:

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

下面是我的代码:

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>

如果有人帮助我,那就太好了。

【问题讨论】:

    标签: reactjs datatable mui-datatable


    【解决方案1】:

    您直接改变状态以更新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() 将组件状态的更改排入队列并告诉 React 这个组件及其子组件需要重新渲染 更新状态。

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

    【讨论】:

    • 它按预期工作。非常感谢!实际上,我总是按照我提到的方式来做。
    猜你喜欢
    • 2021-04-03
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多